ZF2,class 实现 FactoryInterface 将 ServiceLocator 实例作为属性传递
ZF2, class implementing FactoryInterface pass ServiceLocator instance as attribute
我有一个实现 FactoryInterface
的工厂,例如:
class SomeFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
// the code to create SomeClass instance
}
}
现在,所有代码都在 createService
方法中(多个 if
s、一些查询等),这使得该方法冗长且难以遵循。我想通过将一些代码片段提取到单独的方法中来重构代码。问题是我的情况,我最终在这些方法中的每一个中都传递了 $serviceLocator->getServiceLocator()
的实例,这确实没问题,但感觉很难看。
我想知道是否有一种优雅的方法可以分配 SomeFactory
$serviceLocator->getServiceLocator()
的属性,而不是在每个提取的方法中传递它。
我觉得你不太了解 Factories 的用法。
工厂仅用于在另一个对象中注入依赖项,例如 Controller
或 Service
。
所以,当然,这取决于你想做什么,但我认为你想创建一个 Service
来做一些思考。
示例:
class MyService implements ServiceLocatorAwareInterface
{
use ServiceLocatorAwareTrait; // used to inject SL getter and setter in your code
public function myMethod1()
{
$formElementManager = $this->getServiceLocator()->get('formElementManager');
// ... etc ...
}
public function myMethod9999() ......
}
class MyServiceFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$myService = new MyService();
$myService->setServiceLocator($serviceLocator);
$myService->setAnotherProperty(...);
return $myService;
}
}
如果你的MyService()
class中确实需要ServiceLocator
,建议在__construct()
方法中注入
我有一个实现 FactoryInterface
的工厂,例如:
class SomeFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
// the code to create SomeClass instance
}
}
现在,所有代码都在 createService
方法中(多个 if
s、一些查询等),这使得该方法冗长且难以遵循。我想通过将一些代码片段提取到单独的方法中来重构代码。问题是我的情况,我最终在这些方法中的每一个中都传递了 $serviceLocator->getServiceLocator()
的实例,这确实没问题,但感觉很难看。
我想知道是否有一种优雅的方法可以分配 SomeFactory
$serviceLocator->getServiceLocator()
的属性,而不是在每个提取的方法中传递它。
我觉得你不太了解 Factories 的用法。
工厂仅用于在另一个对象中注入依赖项,例如 Controller
或 Service
。
所以,当然,这取决于你想做什么,但我认为你想创建一个 Service
来做一些思考。
示例:
class MyService implements ServiceLocatorAwareInterface
{
use ServiceLocatorAwareTrait; // used to inject SL getter and setter in your code
public function myMethod1()
{
$formElementManager = $this->getServiceLocator()->get('formElementManager');
// ... etc ...
}
public function myMethod9999() ......
}
class MyServiceFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$myService = new MyService();
$myService->setServiceLocator($serviceLocator);
$myService->setAnotherProperty(...);
return $myService;
}
}
如果你的MyService()
class中确实需要ServiceLocator
,建议在__construct()
方法中注入