簡體   English   中英

使用 DI->Get Phalcon PHP 時出現“無效的服務定義”

[英]"Invalid Service Definition" when using DI->Get Phalcon PHP

這個問題與Appending multiple config arrays in PhalconPHP 有關

我正在嘗試使用 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' 帶有消息 '無效的服務定義。 缺少 'className' 參數']

我已經堅持了幾天了,所以非常感謝我能得到的任何幫助。

在集合中試試這個:

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

看起來你在做$di->set('config', $new_array); 而不是$di->set('config', $config); :)

如果您的 $config 變量是一個數組。 您可以在Missing 'className' 參數中參考我的答案

這是轉帖:我發現 Phalcon DI 容器使用數組進行構造函數注入。 因此,如果您將數組設置到 Phalcon DI 容器中,它會理解您要使用構造函數注入來設置對象,並且需要“className”定義。 您可以在https://docs.phalconphp.com/3.4/en/di 的構造函數注入部分進行檢查。

文檔中構造函數注入示例:

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

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

我的解決方案:

  1. 假設我想將此配置數組 ['key' => 'value'] 設置為 DI。
  2. 我創建了 MyConfigFactory 類,該類具有返回 ['key' => 'value'] 的函數 build。
  3. 我注入我的配置如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM