1

I'm using Slim Framework with PHP-DI to autowire dependencies for me. But one dependency is just a regular array. If I put a regular array into my container configuration, then all arrays will be set to that one array. So my primary question would be:

How do I inject just one single variable, while letting the container auto-wire the rest? Is this possible? I've found myself writing a route like this:

$app->get('/userConfig', function (
    Request $request, 
    Response $response,
    Preferences $prefs,
    UserConfig $userconfig)
{
    $myArray = ['Thing1','thing2','thing3'];
    return $userconfig->configView($request, $response, $myArray, $prefs);
});

Whereas all my other routes are short like this, because they only have dependencies on unique classes:

$app->get('/testPage', ['\Test','myTestPage']);

I wrote all that extra stuff just to squeeze $myArray into the configView function, is there a way to combine regular dependency injection with autowiring? Does any framework or library do that?

I could have just written it like this if I didn't need that one array:

$app->get('/userConfig', ['\UserConfig','configView']);

Alternatively, I could reach into the container and get the array, but that would make the page-function dependent on the container, which is something which should be avoided.

4

2 回答 2

1

你不能只用自动装配来解决这个问题。您必须编写一些配置才能将数组注入您需要的类中:http: //php-di.org/doc/php-definitions.html

另请参阅此处以阅读如何使用 Slim 和 PHP-DI 设置配置文件:http: //php-di.org/doc/frameworks/slim.html#configuring-php-di

于 2016-11-24T10:02:57.717 回答
0

我需要使用容器的 call() 函数。正如您在问题中看到的那样,configView 还有一个“首选项”参数,但是我不必传递它,容器为我做了。我不明白如何将部分参数集传递给它,这就是如何作为 call() 的第二个参数中的数组,如下所示:

$app->get('/userConfig', function (
        Request $request, 
        Response $response
    ){
        $myArray = ['Thing1','thing2','thing3'];
        return $this->call(['UserConfig', 'configView'],[$request,$response,$myArray]);
    });

关键部分是[$request,$response,$myArray]并且不需要所有其他参数。在我的示例中只有一个,但我的实际对象还有 5 个,我想知道如何避免处理其他参数,这就是...

于 2016-11-30T22:44:47.857 回答