2017-10-19 299 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如果也有一个工厂。