“Invalid Service Definition” when using DI->Get Phalcon PHP

做~自己de王妃 提交于 2019-12-02 06:17:34

Try this instead in the set:

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

It looks like you're doing $di->set('config', $new_array); instead of $di->set('config', $config); :)

If your $config variable is an array. You can refer my answer at Missing 'className' parameter

Here is the repost: I found that Phalcon DI container use array for Constructor Injection. So if you set an array into Phalcon DI container, it understands that you want to set an object by using Constructor Injection and it requires "className" definition. You can check this at Constructor Injection section at https://docs.phalconphp.com/3.4/en/di.

Example of constructor injection in the document:

$di->set(
    'response',
    [
        'className' => 'Phalcon\Http\Response'
    ]
);

$di->set(
    'someComponent',
    [
        'className' => 'SomeApp\SomeComponent',
        'arguments' => [
            [
                'type' => 'service',
                'name' => 'response',
            ],
            [
                'type'  => 'parameter',
                'value' => true,
            ],
        ]
    ]
);

MY SOLUTION:

  1. Suppose that I want to set this config array ['key' => 'value'] into DI.
  2. I create MyConfigFactory class, which has function build to return ['key' => 'value'].
  3. I inject my config as below:

    $di->set('myConfigFactory', new MyConfigFactory());
    $di->set('config', function () use ($di) {
        return $di->get('myConfigFactory')->build();
    });
    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!