symfony - 从 Symfony 中的动态 ID 获取服务
问题描述
我想将服务 ID 集中到实体类中并以这种方式实现我的逻辑:
namespace App\Entity;
interface EntityServiceInterface
{
public function getServiceId: string;
}
namespace App\Entity;
class EntityA implements EntityServiceInterface
{
public function getServiceId(): string
{
return EntityServiceA::class;
}
}
namespace App\Entity;
class EntityB implements EntityServiceInterface
{
public function getServiceId(): string
{
return EntityServiceB::class';
}
}
namespace App\Service;
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 App\Service;
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 App\Service;
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();
}
}
}
正如我们所知,将 ContainerInterface 注入服务不是一个好主意,但我需要它通过实体类中定义的 ID 来获取我的服务。
如何在不使用 ContainerInterface 的情况下动态获取服务?
在 Symfony 3.4中运行。
如果您需要更多信息,请询问,我会更新问题。
解决方案
推荐阅读
- rust - 在嵌套数组索引中,“不能作为不可变借用,因为它也作为可变借用”是什么意思?
- angular - 路由更改时角度数据不会持续存在
- r - 如何使用索引使用 dplyr 重构非常宽的数据帧?
- python - 类型错误:预期字节,找到描述符
- docker - Ubuntu 上的 Docker 主机占用了 VM 上的所有空间
- laravel - Laravel 验证有效,但返回 200 而不是 422
- ansible - 在任务条件中使用 ansible 变量
- javascript - 使用 Leaflet 和 Vue.js 创建地图
- python - 如何在 Python 中将字符串的第一个字母大写,而忽略 HTML 标记?
- java - 查找给定日期的所有过帐日期(会计)