自zend-mvc版本2.7.0开始,ServiceLocatorAwareInterface
被删除,$this->serviceLocator->get()
调用在控制器内。在没有serviceLocator-> get()方法的情况下,ZF2中依赖注入的新方法效率更低?
这就是为什么前几天我做了大量的重构我的所有模块,通过使用工厂的构造函数注入所需的服务/对象主要是所有东西。
当然,我明白为什么这是更好/更干净的方式来做事情,因为现在依赖项更加可见。但另一方面:
这导致了大量的开销和更多未使用的类实例,不是吗?
让我们来看一个例子:
因为有依赖我所有的控制器中,我创建的工厂为他们所有。
CustomerControllerFactory.php
namespace Admin\Factory\Controller;
class CustomerControllerFactory implements FactoryInterface {
public function createService(ServiceLocatorInterface $controllerManager) {
$serviceLocator = $controllerManager->getServiceLocator();
$customerService = $serviceLocator->get('Admin\Service\CustomerService');
$restSyncService = $serviceLocator->get('Admin\Service\SyncRestClientService');
return new \Admin\Controller\CustomerController($customerService, $restSyncService);
}
}
CustomerController.php
namespace Admin\Controller;
class CustomerController extends AbstractRestfulController {
public function __construct($customerService, $restSyncService) {
$this->customerService = $customerService;
$this->restSyncService = $restSyncService;
}
}
module.config.php
'controllers' => [
'factories' => [
'Admin\Controller\CustomerController' => 'Admin\Factory\Controller\CustomerControllerFactory',
]
],
'service_manager' => [
'factories' => [
'Admin\Service\SyncRestClientService' => 'Admin\Factory\SyncRestClientServiceFactory',
]
]
SyncRestClientServiceFactory.php
namespace Admin\Factory;
class SyncRestClientServiceFactory implements FactoryInterface {
public function createService(ServiceLocatorInterface $serviceLocator) {
$entityManager = $serviceLocator->get('doctrine.entitymanager.orm_default');
$x1 = $serviceLocator->get(...);
$x2 = $serviceLocator->get(...);
$x3 = $serviceLocator->get(...);
// ...
return new \Admin\Service\SyncRestClientService($entityManager, $x1, $x2, $x3, ...);
}
}
的SyncRestService是一个复杂的服务类,查询我们系统内部的一些服务器。它有很多依赖关系,并且如果请求发送到CustomerController,则始终创建它。但是这个同步服务是只有在CustomerController的syncAction()
里面使用!在我使用syncAction()
之前只需使用$this->serviceLocator->get('Admin\Service\SyncRestClientService')
,所以只有在它被实例化之前。
通常看起来很多实例是通过工厂在每个请求中创建的,但大多数依赖关系不被使用。这是由于我的设计问题,还是“通过构造函数进行依赖注入”的正常副作用行为?
我在这里问了几乎相同的问题:http://stackoverflow.com/questions/33496279/servicelocator-lets-thoughts-about-it-in-zf2-context – Hooli