&引用;无效的服务定义“;使用DI时->;获取Phalcon PHP

&引用;无效的服务定义“;使用DI时->;获取Phalcon PHP,php,phalcon,Php,Phalcon,这个问题与 我正在尝试使用get方法从DI获取一个对象 对象被设置为这样 // $new_array the array with the merged data. Load it in a // \Phalcon\Config object $config = new \Phalcon\Config($new_array); //Store the config in your DI container for easier use $di->set('config', $confi

这个问题与

我正在尝试使用get方法从DI获取一个对象

对象被设置为这样

// $new_array the array with the merged data. Load it in a 
// \Phalcon\Config object
$config = new \Phalcon\Config($new_array);

//Store the config in your DI container for easier use
$di->set('config', $config);
这是我打电话时收到的错误信息

$new_array = $di->get('config');
[未捕获异常'Phalcon\DI\exception',消息'Invalid 服务定义。缺少“className”参数“]


这件事我已经坚持了好几天了,所以如果能得到任何帮助,我将不胜感激。

看起来你正在做
$di->set('config',$new\u array)而不是
$di->set('config',$config):)

在集合中尝试以下操作:

$di->set('config', function() {
   ...
   return new \Phalcon\Config($new_array);
});

如果$config变量是数组。你可以参考我的答案

以下是报告: 我发现Phalcon DI容器使用数组进行构造函数注入。所以,如果您在Phalcon DI容器中设置一个数组,它会理解您想要通过使用构造函数注入来设置一个对象,并且它需要“className”定义。您可以在的构造函数注入部分检查这一点

文档中的构造函数注入示例:
$di->set(
    'response',
    [
        'className' => 'Phalcon\Http\Response'
    ]
);

$di->set(
    'someComponent',
    [
        'className' => 'SomeApp\SomeComponent',
        'arguments' => [
            [
                'type' => 'service',
                'name' => 'response',
            ],
            [
                'type'  => 'parameter',
                'value' => true,
            ],
        ]
    ]
);
我的解决方案:

  • 假设我想将这个配置数组['key'=>'value']设置为DI
  • 我创建了MyConfigFactory类,该类的函数build返回['key'=>'value']
  • 我注入我的配置如下:

    $di->set('myConfigFactory', new MyConfigFactory());
    $di->set('config', function () use ($di) {
        return $di->get('myConfigFactory')->build();
    });
    

  • 使用[setShared]避免每次调用get时重新创建配置