我試圖實現依賴注入使用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',
)
),
你確定'factory'在'controller'數組中嗎?它應該在'service_manager'中。 – akond