2017-10-19 204 views
0

我試圖實現依賴注入使用Zend2服務管理器。我想將一個PDO實例注入Service(我不使用Zend Db)。Zend2依賴注入工廠服務

進出口以下教程這裏:https://framework.zend.com/manual/2.4/en/in-depth-guide/services-and-servicemanager.html

我有工作的另一項服務,但注入PDO例如即時得到這個錯誤時:

Catchable fatal error: Argument 1 passed to Application\Service\DataService::__construct() must be an instance of Application\Service\DbConnectorService, none given, called in /srv/www/shared-apps/approot/apps-dev/ktrist/SBSDash/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php on line 1077 and defined in /srv/www/shared-apps/approot/apps-dev/ktrist/SBSDash/module/Application/src/Application/Service/DataService.php on line 24

從這個似乎是相關教程到我在module.config中的可調參數。但我無法弄清楚問題所在。

任何意見表示讚賞。

這裏是我的代碼:

的DataService:

class DataService { 
protected $dbConnectorService; 

public function __construct(DbConnectorService $dbConnectorService) { 
    $this->dbConnectorService = $dbConnectorService; 
} 
...... 

DataServiceFactory:

namespace Application\Factory; 

use Application\Service\DataService; 
use Zend\ServiceManager\FactoryInterface; 
use Zend\ServiceManager\ServiceLocatorInterface; 

class DataServiceFactory implements FactoryInterface { 

function createService(ServiceLocatorInterface $serviceLocator) { 
    $realServiceLocator = $serviceLocator->getServiceLocator(); 
    $dbService = $realServiceLocator->get('Application\Service\DbConnectorService'); 

    return new DataService($dbService); 
} 

} 

Module.Config:

'controllers' => array(
'factories' => array(
     'Application\Controller\Index' => 'Application\Factory\IndexControllerFactory', 
     'Application\Service\DataService' => 'Application\Factory\DataServiceFactory', 
    ) 
), 
    'service_manager' => array(
    'invokables' => array(
     'Application\Service\DataServiceInterface' => 'Application\Service\DataService', 
     'Application\Service\DbConnectorService' => 'Application\Service\DbConnectorService', 
    ) 
), 
+0

你確定'factory'在'controller'數組中嗎?它應該在'service_manager'中。 – akond

回答

2

您正試圖創建作爲服務一個'invokable '班。 ZF2將把這個服務視爲一個沒有依賴關係的類(而不是使用工廠創建它)。

您應該更新您的服務配置以註冊'factories'密鑰,指向工廠類名稱。

'service_manager' => [ 
    'invokables' => [ 
     'Application\\Service\\DbConnectorService' 
      => 'Application\\Service\\DbConnectorService', 
    ], 
    'factories' => [ 
     'Application\\Service\\DataServiceInterface' 
      => 'Application\\Factory\\DataServiceFactory', 
    ], 
], 

您需要進行同樣的更改對DbConnectorService如果也有一個工廠。