Zend2 依赖注入工厂服务

Zend2 Dependency injection factory to service

我正在尝试使用 Zend2 服务管理器实施依赖注入。我想将 PDO 实例注入服务(我没有使用 Zend Db)。

我正在按照这里的教程进行操作: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 中的可调用对象有关。但是我不知道是什么问题。

如有任何建议,我们将不胜感激。

这是我的代码:

数据服务:

class DataService {
protected $dbConnectorService;

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

数据服务工厂:

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',
    )
),

您正在尝试将服务创建为 'invokable' class。 ZF2 会将此服务视为没有依赖项的 class(并且不会使用工厂创建它)。

您应该更新您的服务配置以在 'factories' 键下注册,指向 factory class 名称。

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

如果 DbConnectorService 也有工厂,您将需要对其进行相同的更改。