Get services from dynamic ID in Symfony

I would like to centralize service IDs into Entity classes and implements my logic this way :

namespace AppEntity;

interface EntityServiceInterface
{
    public function getServiceId: string;
}
namespace AppEntity;

class EntityA implements EntityServiceInterface
{
    public function getServiceId(): string
    {
        return EntityServiceA::class;
    }
}
namespace AppEntity;

class EntityB implements EntityServiceInterface
{
    public function getServiceId(): string
    {
        return EntityServiceB::class';
    }
}
namespace AppService;

class EntityServiceA
{
    private LoggerInterface $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function doSomething(): string
    {
        return $this->logger->info('I love Entity A !');
    }
}
namespace AppService;

class EntityServiceB
{
    private LoggerInterface $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function doSomething(): string
    {
        return $this->logger->info('I love Entity B !');
    }
}
namespace AppService;

class MyService
{
    private $container;

    /**
     * Injecting ContainerInterface is a bad idea but i need it !
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process($entity): void
    {
        if ($entity instanceof EntityServiceInterface) {
            $service = $this->container->get(entity->getServiceId());

            $service->doSomething();
        }
    }
}

As we know, injecting ContainerInterface into Services is not a good idea but I need it to get my services by their ID defined in Entity classes.

How to get services dynamically without using ContainerInterface ?

Running in Symfony 3.4.

If you need more info, just ask and I will update the question.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *