【问题标题】:Symfony - how to choose the right interface (type-hint) for symfony services?Symfony - 如何为 symfony 服务选择正确的接口(类型提示)?
【发布时间】:2018-12-14 11:18:17
【问题描述】:

我经常在包含 oder 猜测正确的界面时遇到困难 包括一项服务。例如,这是获取路由器的推荐方式。

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class SomeService
{
    private $router;

    public function __construct(UrlGeneratorInterface $router)
    {
        $this->router = $router;
    }
}

我想,我在这里得到的是“vendor\symfony\routing\Router.php”。 但是Router类实现了RouterInterface、RequestMatcherInterface。 不是 UrlGeneratorInterface!

我不明白这背后的逻辑。 感谢您的帮助。

【问题讨论】:

  • 这可能是卷起袖子深入研究源代码的最佳选择。生成器接口提供了一个 generate 方法,它是最常用的。您的 $router 变量确实应该称为 $generator。问题是,RouterInterface 扩展了 UrlGeneratorInterface 和 UrlMatcherInterface。所以它既可以生成又可以匹配。我倾向于使用 RouterInterface 只是因为拥有一个路由器对象似乎更容易理解。尽管我很少需要匹配功能。

标签: php symfony namespaces


【解决方案1】:

https://symfony.com/doc/current/service_container/autowiring.html#working-with-interfaces

实践实际上是将您键入提示的接口别名为您想要注入的类。因此,如果您想注入与Router 不同的类,请在services.yml 中执行:

// services.yml
services:
    App\Util\Router: ~

    Symfony\Component\Routing\Generator\UrlGeneratorInterface: '@App\Util\Router'

只要只有一个类实现接口并且该类是同一命名空间的一部分,配置别名不是强制性的,Symfony 会自动创建一个。

为什么您的案例有效?继承。

https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Routing/RouterInterface.php

interface RouterInterface extends UrlMatcherInterface, UrlGeneratorInterface

【讨论】:

  • 关闭但不完全。 “bin/console debug:container | grep Url”显示 UrlGeneratorInterface 和 UrlMatcherInterface 都有明确定义为 router.default 的别名。这就是为什么注入工作但无论如何你总是得到一个路由器对象的原因。真的有点hack。而且,尽管文档暗示了什么,为给定接口定义一个且只有一个服务的整个事情并不总是按预期工作。
猜你喜欢
  • 2021-05-11
  • 2016-06-10
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 2017-01-09
  • 2018-07-27
  • 1970-01-01
  • 2013-08-08
相关资源
最近更新 更多