A dependency injection (DI) container is an object that knows how to instantiate and configure objects and all their dependent objects. For more information about DI, please refer to Martin Fowler's article. Container supports constructor injection as well as property injection. To use Container, you first need to set up the class dependencies by calling Container::set. You then call Container::get to create a new class object. Container will automatically instantiate dependent objects, inject them into the object being created, configure and finally return the newly created object. By default, [[\Yii::$container]] refers to a Container instance which is used by [[\Yii::createObject()]] to create new object instances. You may use this method to replace the new operator when creating a new object, which gives you the benefit of automatic dependency resolution and default property configuration. Below is an example of using Container: php namespace app\models; use yii\base\Object; use yii\db\Connection; use yii\di\Container; interface UserFinderInterface { function findUser(); } class UserFinder extends Object implements UserFinderInterface { public $db; public function __construct(Connection $db, $config = []) { $this->db = $db; parent::__construct($config); } public function findUser() { } } class UserLister extends Object { public $finder; public function __construct(UserFinderInterface $finder, $config = []) { $this->finder = $finder; parent::__construct($config); } } $container = new Container; $container->set('yii\db\Connection', [ 'dsn' => '...', ]); $container->set('app\models\UserFinderInterface', [ 'class' => 'app\models\UserFinder', ]); $container->set('userLister', 'app\models\UserLister'); $lister = $container->get('userLister'); which is equivalent to: $db = new \yii\db\Connection(['dsn' => '...']); $finder = new UserFinder($db); $lister = new UserLister($finder); For more details and usage information on Container, see the guide article on di-containers.
부터: 2.0
저자: Qiang Xue (qiang.xue@gmail.com)
상속: extends yii\base\Component
예제 #1
0
 protected function initEventHandlers(Container $container)
 {
     $this->on(self::EVENT_OBJECT_CHANGED, function (ObjectHistoryEvent $event) use($container) {
         /** @var contracts\ObjectHistoryManagerInterface $objectHistoryManager */
         $objectHistoryManager = $container->get('entityfx\\utils\\objectHistory\\contracts\\ObjectHistoryManagerInterface');
         $objectHistoryManager->objectModified($event->historyType, $event->guid, $event->category);
     });
 }
예제 #2
0
파일: InstanceTest.php 프로젝트: howq/yii2
 public function testEnsure()
 {
     $container = new Container();
     $container->set('db', ['class' => 'yii\\db\\Connection', 'dsn' => 'test']);
     $this->assertTrue(Instance::ensure('db', 'yii\\db\\Connection', $container) instanceof Connection);
     $this->assertTrue(Instance::ensure(new Connection(), 'yii\\db\\Connection', $container) instanceof Connection);
     $this->assertTrue(Instance::ensure(['class' => 'yii\\db\\Connection', 'dsn' => 'test'], 'yii\\db\\Connection', $container) instanceof Connection);
 }
예제 #3
0
 /**
  * @param $from
  * @param $to
  * @param $data
  * @return mixed
  */
 public function convert($from, $to, $data)
 {
     $executor = new Executor();
     $decoder = $this->container->get($from);
     $encoder = $this->container->get($to);
     $executor->setDecodeService($decoder);
     $executor->setEncodeService($encoder);
     return $executor->transform($data);
 }
예제 #4
0
 public function testDefault()
 {
     $namespace = __NAMESPACE__ . '\\stubs';
     $QuxInterface = "{$namespace}\\QuxInterface";
     $Foo = Foo::className();
     $Bar = Bar::className();
     $Qux = Qux::className();
     // automatic wiring
     $container = new Container();
     $container->set($QuxInterface, $Qux);
     $foo = $container->get($Foo);
     $this->assertTrue($foo instanceof $Foo);
     $this->assertTrue($foo->bar instanceof $Bar);
     $this->assertTrue($foo->bar->qux instanceof $Qux);
     // full wiring
     $container = new Container();
     $container->set($QuxInterface, $Qux);
     $container->set($Bar);
     $container->set($Qux);
     $container->set($Foo);
     $foo = $container->get($Foo);
     $this->assertTrue($foo instanceof $Foo);
     $this->assertTrue($foo->bar instanceof $Bar);
     $this->assertTrue($foo->bar->qux instanceof $Qux);
     // wiring by closure
     $container = new Container();
     $container->set('foo', function () {
         $qux = new Qux();
         $bar = new Bar($qux);
         return new Foo($bar);
     });
     $foo = $container->get('foo');
     $this->assertTrue($foo instanceof $Foo);
     $this->assertTrue($foo->bar instanceof $Bar);
     $this->assertTrue($foo->bar->qux instanceof $Qux);
     // wiring by closure which uses container
     $container = new Container();
     $container->set($QuxInterface, $Qux);
     $container->set('foo', function (Container $c, $params, $config) {
         return $c->get(Foo::className());
     });
     $foo = $container->get('foo');
     $this->assertTrue($foo instanceof $Foo);
     $this->assertTrue($foo->bar instanceof $Bar);
     $this->assertTrue($foo->bar->qux instanceof $Qux);
     // predefined constructor parameters
     $container = new Container();
     $container->set('foo', $Foo, [Instance::of('bar')]);
     $container->set('bar', $Bar, [Instance::of('qux')]);
     $container->set('qux', $Qux);
     $foo = $container->get('foo');
     $this->assertTrue($foo instanceof $Foo);
     $this->assertTrue($foo->bar instanceof $Bar);
     $this->assertTrue($foo->bar->qux instanceof $Qux);
 }
예제 #5
0
 /**
  * @return Container
  */
 private static function getIoc()
 {
     $diConfig = (include 'di.php');
     $container = new Container();
     $container->setSingleton('workerMapper', $diConfig['workerMapper']);
     $container->setSingleton('entityfx\\utils\\workers\\contracts\\repositories\\WorkerRepositoryInterface', function ($container, $params, $config) use($diConfig) {
         return $container->get($diConfig['workerRepository'], [$container->get('workerMapper')]);
     });
     $container->set('entityfx\\utils\\workers\\contracts\\WorkerInterceptorInterface', function ($container, $params, $config) use($diConfig) {
         return $container->get($diConfig['workerInterceptor'], [$params['worker'], $container->get('entityfx\\utils\\workers\\contracts\\repositories\\WorkerRepositoryInterface')]);
     });
     return $container;
 }
예제 #6
0
 /**
  * Generate fake data and
  */
 public function actionGenerate()
 {
     $input = $this->parseArguments(func_get_args());
     $container = new Container();
     $container->set(GeneratorInterface::class, array_merge(['class' => $this->generator_fqn], $input['generator']));
     $container->set(DbProviderInterface::class, array_merge(['class' => $this->dbprovider_fqn], $input['dbprovider']));
     $this->generator_obj = $container->get(GeneratorInterface::class);
     if (!$this->force && !$this->confirmGeneration()) {
         return;
     }
     $this->dbprovider_obj = $container->get(DbProviderInterface::class);
     Console::startProgress(0, $this->count);
     foreach ($this->dbprovider_obj->export($this->count) as $count) {
         Console::updateProgress($this->count - $count, $this->count);
     }
     Console::endProgress(true);
 }
예제 #7
0
 /**
  * @return Container
  */
 private static function getIoc()
 {
     //$diConfig = include('di.php');
     $diConfig = [];
     $container = new Container();
     $container->setSingleton('clientProxyMapper', 'app\\utils\\webService\\implementation\\clientProxies\\mapper\\ClientProxyMapper');
     $container->setSingleton('app\\utils\\webService\\contracts\\clientProxies\\repositories\\WebClientProxyRepositoryInterface', function ($container, $params, $config) use($diConfig) {
         return $container->get('app\\utils\\webService\\implementation\\clientProxies\\repositories\\WebClientProxyRepository', [$container->get('clientProxyMapper')]);
     });
     /*$container->set('app\utils\workers\contracts\WorkerInterceptorInterface',
       function($container, $params, $config) use ($diConfig) {
           return  $container->get(
               $diConfig['workerInterceptor'],
               [$params['worker'], $container->get('app\utils\workers\contracts\repositories\WorkerRepositoryInterface')]
           );
       });*/
     return $container;
 }
예제 #8
0
 public function createUrl($params)
 {
     $params = is_string($params) ? [0 => $params] : $params;
     $languagePovider = $this->conteiner->get('languageProvider');
     $languages = $languagePovider->getLanguages();
     $receive = new ReceiveContainer();
     $receive->addReceiver(new ParamsLanguageReceive($params, $this->languageKey));
     if ($this->detectInSession) {
         $receive->addReceiver(new SessionLanguageReceive($this->sessionLanguageKey));
     }
     if ($this->detectInCookie) {
         $receive->addReceiver(new CookieLanguageReceive($this->cookieLanguageKey));
     }
     $language = $receive->getLanguage();
     unset($params[$this->languageKey]);
     if (!isset($language)) {
         $language = \Yii::$app->language;
     }
     $this->language = $language;
     //        $language = isset($language) ? $language : $this->language;
     $language = $this->lowerCase ? strtolower($language) : $language;
     $language = $this->useShortSyntax ? preg_replace('~(\\w{2})-\\w{2}~i', '$1', $language, 1) : $language;
     return $this->showDefault || strcasecmp($language, $this->defaultLanguage) != 0 ? substr_replace(parent::createUrl($params), !empty($language) ? "/{$language}" : '', strlen($this->baseUrl), 0) : parent::createUrl($params);
 }
예제 #9
0
 /**
  * 待改进 未测试
  * @param \yii\di\Container $container
  * @param array $serviceConfig
  */
 public function configureContainer($container, $serviceConfig)
 {
     foreach ($serviceConfig as $class => $definition) {
         $container->set($class, $definition);
     }
 }
 /**
  * @dataProvider dataProviderConfigurable
  *
  * @param ContainerConfiguratorTestStubYiiBaseObject|ContainerConfiguratorTestStubYiiBaseConfigurable|string $class
  *
  * @throws WrongConfigException
  */
 public function testConfigurable($class)
 {
     if (!class_exists($class, false)) {
         $this->markTestSkipped("Class '{$class}' not found, maybe yii2 old version, it's ok");
     }
     $config = ['service' => ['class' => $class, 'arguments' => [['type' => ContainerConfigurator::ARGUMENT_TYPE_VALUE, 'value' => 'argument1value'], ['type' => ContainerConfigurator::ARGUMENT_TYPE_VALUE, 'value' => 'argument2value']], 'properties' => ['property1' => ['type' => ContainerConfigurator::ARGUMENT_TYPE_VALUE, 'value' => 'property1value'], 'property2' => ['type' => ContainerConfigurator::ARGUMENT_TYPE_VALUE, 'value' => 'property2value']]]];
     $container = new Container();
     $containerConfigurator = new ContainerConfigurator($container);
     $containerConfigurator->configure($config);
     /** @var ContainerConfiguratorTestStubYiiBaseObject|ContainerConfiguratorTestStubYiiBaseConfigurable $stub */
     $stub = $container->get('service');
     $class::test($this, ['class' => $config['service']['class'], 'arguments' => ['argument1value', 'argument2value', ['property1' => 'property1value', 'property2' => 'property2value']]], $stub);
 }
예제 #11
-2
 /**
  * Returns the actual object referenced by this Instance object.
  * @param ServiceLocator|Container $container the container used to locate the referenced object.
  * If null, the method will first try `Yii::$app` then `Yii::$container`.
  * @return object the actual object referenced by this Instance object.
  */
 public function get($container = null)
 {
     if ($container) {
         return $container->get($this->id);
     }
     if (Yii::$app && Yii::$app->has($this->id)) {
         return Yii::$app->get($this->id);
     } else {
         return Yii::$container->get($this->id);
     }
 }