I'm able to do this on my configuration file:
'container' => [
'definitions' => [
'Foo' => function () {
$foo = new Foo(new Bar);
// ... other initializations ...
return $foo;
}
]
]
So Yii::$container->get('Foo') works as expected, however I want to hide the complex logic by using a static class method as callable like this example, here is what I've done:
'container' => [
'definitions' => [
'Foo' => ['app\helper\FooBuilder', 'build']
]
]
A new instance of the Foo class
Fatal error: Uncaught TypeError: Argument 3 passed to yii\di\Container::set() must be of the type
array, string given, called in /var/www/vendor/yiisoft/yii2/di/Container.php
on line 620 and defined in /var/www/vendor/yiisoft/yii2/di/Container.php:252
Stack trace:
#0 /var/www/vendor/yiisoft/yii2/di/Container.php(620): yii\di\Container->set('webDriver', 'app\\helpers\\FooBuilder', 'build')
#1 /var/www/vendor/yiisoft/yii2/base/Component.php(172): yii\di\Container->setDefinitions(Array)
#2 /var/www/vendor/yiisoft/yii2/BaseYii.php(529): yii\base\Component->__set('definitions', Array)
#3 /var/www/vendor/yiisoft/yii2/base/Application.php(671): yii\BaseYii::configure(Object(yii\di\Container), Array)
#4 /var/www/vendor/yiisoft/yii2/base/Application.php(251): yii\base\Application->setContainer(Array)
#5 /var/www/vendor/yiisoft/yii2/base/Application.php(201): yii\base\Application->preInit(Array)
#6 /var/www/web/index.php(12): yii\base\Application->__construct(Array)
#7 {main} thrown in /var/www/vendor/yiisoft/yii2/di/Container.php on line 252
| Q | A
| ---------------- | ---
| Yii version | 2.0.12
| PHP version | 7.1.3
| Operating system | macOS 10.13
Array of two elements as definition has different meaning for assignment using config. See Advanced Practical Usage.
Try this instead:
'container' => [
'definitions' => [
'Foo' => Closure::fromCallable(['app\helper\FooBuilder', 'build'])
]
]
Thank you for your question.
In order for this issue tracker to be effective, it should only contain bug reports and feature requests.
We advise you to use our community driven resources:
If you are confident that there is a bug in the framework, feel free to provide information on how to reproduce it. This issue will be closed for now.
_This is an automated comment, triggered by adding the label question._
Most helpful comment
Array of two elements as definition has different meaning for assignment using config. See Advanced Practical Usage.
Try this instead: