简体   繁体   English

Symfony2 - 如何注入可选参数

[英]Symfony2 - How to inject an optional parameter

Let's say I have a forum service. 假设我有一个论坛服务。 This service needs an URL to the forum API. 此服务需要一个论坛API的URL。 What I want is that URL to be either internal or external. 我想要的是该URL是内部的还是外部的。

If internal , it would be a route , configured in routing.yml and returned by the router service. 如果是内部的 ,它将是路由 ,在routing.yml中配置并由路由器服务返回。

If external , it would be a parameter , configured in parameters.yml. 如果是外部的 ,它将是参数 ,在parameters.yml中配置。

The approach I've thought of is: 我想到的方法是:

Look for the variable forum_url in parameters.yml. 在parameters.yml中查找变量forum_url。 If it doesn't exist, try to obtain that route. 如果它不存在,请尝试获取该路线。 Else, throw Exception. 否则,抛出异常。

services:
    forums:
        class: Acme\ForumsBundle\ForumService
        arguments: ["@doctrine.orm.entity_manager","@router", "%forum_url%"]

The problem with this implementation is that, if the variable is not defined, it throws an exception so what I would need is to define it as an optional parameter (like you can do with services ( "@?service" ). 这个实现的问题是,如果没有定义变量,它会抛出一个异常,所以我需要的是将它定义为一个可选参数 (就像你可以用服务( “@?service” )一样。

What would be EVEN COOLER would be to be able to define something like: 即使是冷却器也能够定义如下内容:

"%forum_url% ? %forum_url% : @router"

Any ideas on how to achieve any of this? 关于如何实现这一目标的任何想法?

PS: If there is another "better practice" approach, I'm open to inputs. PS:如果还有另一种“更好的做法”方法,我愿意接受投入。

You can do it in several ways. 你可以用几种方式做到这一点。

  1. Make %forum_url% not an optional but obligatory parameter but when you intend to have internal url just set null value ( ~ in yml) to %forum_url% parameter. 使%forum_url%不是一个可选但必须参数,但是当你想要内部网址时,只需将null值( ~ %forum_url% in yml)设置为%forum_url%参数。 Then, inject both %forum_url% and @router into your service and check if %forum_url% : if it is not null use it, if it is null use route 然后,将%forum_url%@router注入您的服务并检查%forum_url% :如果它不为null则使用它,如果它为null则使用route

  2. Nicer way would be create another service, let's call it url_resolver . 更好的方式是创建另一个服务,让我们称之为url_resolver You inject this new service into your ForumService . 您将此新服务注入ForumService Inside url_resolver service you do what is described in point 1, so you need obligatory %forum_url% and @router injected. url_resolver服务中,您可以执行第1点中描述的操作,因此您需要注册必需的%forum_url%@router This is just more SOLID way than option 1 这比选项1更简单

  3. Inject whole container into ForumService and check if %forum_url% is set. 将整个容器注入ForumService并检查是否设置了%forum_url% However, note that injecting whole container into service is considered as a bad practice 但是,请注意将整个容器注入服务被认为是一种不好的做法

如果你的symfony版本支持表达式语言,你可以这样做:“@ = container.hasParameter('forum_url')?parameter('forum_url'):service('router')” http://symfony.com/doc /current/service_container/expression_language.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM