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

前端 未结 3 1973
暗喜
暗喜 2021-01-24 15:43

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

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-24 16:22

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

提交回复
热议问题