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

无人久伴 提交于 2020-01-11 11:32:37

问题


This question is related to Appending multiple config arrays in PhalconPHP

I am trying to get retrieve an object from the DI using the get method.

The object is being set like this

// $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);

And this is the error message I am getting when I call

$new_array = $di->get('config');

[Uncaught exception 'Phalcon\DI\Exception' with message 'Invalid service definition. Missing 'className' parameter']

I have been stuck on this for a few days now so would greatly appreciate any help I can get.


回答1:


Try this instead in the set:

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



回答2:


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




回答3:


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();
    });
    


来源:https://stackoverflow.com/questions/13636858/invalid-service-definition-when-using-di-get-phalcon-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!