Symfony. Factorías de servicios

Cómo emplear una factoría para crear y configurar servicios

Factorías de servicios

class FooServiceFactory
{
public static function createFooService()
{
$fooService = new FooService();

// configure service

return $fooService;
}
}
# config/services.yaml
services:
# some code...
App\Service\FooService:
factory: ['App\Service\FooServiceFactory', 'createFooService']
# config/services.yaml
services:
# some code...
App\Service\FooService:
factory: '@App\Service\FooServiceFactory'
class FooServiceFactory
{
public function __invoke()
{
$fooService = new FooService();

// configure service

return $fooService;
}
}

Pasando argumentos a nuestra factoría

# config/services.yaml
services:
# some code...
App\Service\FooService:
factory: '@App\Service\FooServiceFactory'
arguments: ['@doctrine.entity_manager', '%app.some_param%']
use Doctrine\ORM\EntityManagerInterface;...class FooServiceFactory
{
public function __invoke(EntityManagerInterface $em)
{
$fooService = new FooService();

// configure service

return $fooService;
}
}

Factoría de factorías

class PostClassFactory 
{
public function create(array $params)
{
$obj = null
if (some condition based on params) {
$obj = new A();
// logic to set $obj
} else if (some condition based on params) {
$obj = new B();
}
// ...
return $obj;
}
}
class FormProcessor 
{
private $postClassFact;
public function __construct(PostClassFactory $postClassFact)
{
$this->postClassFact = $postClassFact;
}
public function process(array $params)
{
$obj = $this->postClassFact->create($params);
// rest of code
}
}
Image for post
Image for post
class FormProcessor 
{
private $postClassFact;
public function __construct(PostClassFactoryInterface $postClassFact)
{
$this->postClassFact = $postClassFact;
}
public function process(array $params)
{
$obj = $this->postClassFact->create($params);
// rest of code
}
}
Image for post
Image for post
# services.yamlservices: 
...
App\Service\PostClassFactoryInterface:
factory: '@App\Service\CreatePostClassFactory'

Conclusiones

¿Quieres recibir más artículos como este?

Written by

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store