Reputation: 538
I have a factory that implements FactoryInterface
, like:
class SomeFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
// the code to create SomeClass instance
}
}
Now, all the code is inside the createService
method (multiple if
s, some queries, etc.) which makes the method long and difficult to follow. I'd like to refactor the code by extracting the some pieces of code into separate methods. Problem is for my case, I end up passing the instance of $serviceLocator->getServiceLocator()
in each of these methods, which is no problem really, but feels ugly.
I was wondering if there's an elegant way of maybe assigning the attribute of SomeFactory
$serviceLocator->getServiceLocator()
than just passing it in every extracted method.
Upvotes: 0
Views: 54
Reputation: 1684
I think you don't really understand Factories usage.
A factory is ONLY used to inject dependencies in another object, like a Controller
or a Service
.
So, sure, it depends of what you want to do, but I think you want to create a Service
to do some think.
Example :
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;
}
}
If ServiceLocator
is really needed in your MyService()
class, it's recommended to inject it in the __construct()
method
Upvotes: 0