I'm using Symfony 4 for a project, and I have a question regarding factories.
Assume that I have a strategy depending on a kind of string.
I'd like to create differente services, each with own dependencies, based on this props and I'd like to create a factory service, so that the interface is simple.
Let me do an example:
class ServiceBar implements Doing{
public function __construct($dep1,$dep2){
}
public function do();
}
class ServiceBaz implements Doing{
public function __construct($dep3,$dep4){
}
public function do();
}
// Factory Class
class MyServiceFactory{
protected $services = [
'bar' => 'app.service.bar',
'baz' => 'app.service.baz'
];
public function __construct(ContainerInterface $sc){
$this->sc = $sc;
}
public function factory($string){
if(!$this->sc->has($this->services[$string])){
throw new Exception("Missing Service");
}
$this->sc->get($this->services[$string])->do();
}
}
// IndexController.php
public function indexAction(Request $request, MyServiceFactory $factory)
{
$factory->factory($request->get('action'));
}
With this implementation, I have my services created with all dependencies, and a factory called from my controller.
Do you have other ideas, of comment about this solution? I have service container injected withn factory constructor; is there other way to create services from a factory? is there something wrong with this approach?
Thanks in advance