Symfony 控制器中服务的 getter 方法



在控制器中为常用服务设置服务获取器是否是一种好的做法?例如,我的意思是:

class SomeController Extends Contorller {
private function getSomethingManager()
{
return $this->get('myvendorname.something.manager');
}
}

您的示例有点令人困惑,因为您可以直接将 Doctrine 服务与控制器一起使用。如果您使用自动连线功能,则可以将其注入到操作中。

public function test(EntityManagerInterface $em) {
}

然后,您注入了实体管理器,或者您可以使用以下命令将其加载到控制器上:

$this->getDoctrine()->getManager()

所以这不是一个真正好的例子。使用自动连线时,所有类都注册为服务,您可以使用它。

对于数据库查询,您必须使用实体和存储库。

https://symfony.com/doc/current/doctrine.html

如果你在Symfony 3.3以上,你可以使用服务定位器。您可以在服务定位器类中列出所有常用服务。当您需要从任何地方获取特定服务(例如,控制器、命令、服务等(时,您所要做的就是注入类并通过ServiceLocator:locateServiceLocator获取所需的服务。

它非常简单且有用。它还可以帮助您减少依赖注入。查看上面链接中的完整示例。

class ServiceLocator implements ServiceLocatorInterface, ServiceSubscriberInterface
{
private $locator;
public function __construct(ContainerInterface $locator)
{
$this->locator = $locator;
}
public static function getSubscribedServices()
{
return [
ModelFactoryInterface::class,
CalculatorUtilInterface::class,
EntityManagerInterface::class,
AnotherClass::class,
AndAnother::class,
];
}
public function get(string $id)
{
if (!$this->locator->has($id)) {
throw new ServiceLocatorException(sprintf(
'The entry for the given "%s" identifier was not found.',
$id
));
}
try {
return $this->locator->get($id);
} catch (ContainerExceptionInterface $e) {
throw new ServiceLocatorException(sprintf(
'Failed to fetch the entry for the given "%s" identifier.',
$id
));
}
}
}

这就是你使用它的方式:ServiceLocator->locate(AnotherClass::class);

最新更新