xDaizu
xDaizu

Reputation: 1061

Symfony2 - How to inject an optional parameter

Let's say I have a forum service. This service needs an URL to the forum API. What I want is that URL to be either internal or external.

If internal, it would be a route, configured in routing.yml and returned by the router service.

If external, it would be a parameter, configured in parameters.yml.

The approach I've thought of is:

Look for the variable forum_url in parameters.yml. 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").

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.

Upvotes: 1

Views: 1535

Answers (2)

AlTak
AlTak

Reputation: 497

If your symfony version supports expression language than you can do it this way: "@=container.hasParameter('forum_url') ? parameter('forum_url') : service('router')" http://symfony.com/doc/current/service_container/expression_language.html

Upvotes: 1

Tomasz Madeyski
Tomasz Madeyski

Reputation: 10900

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. 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

  2. Nicer way would be create another service, let's call it url_resolver. You inject this new service into your ForumService. Inside url_resolver service you do what is described in point 1, so you need obligatory %forum_url% and @router injected. This is just more SOLID way than option 1

  3. Inject whole container into ForumService and check if %forum_url% is set. However, note that injecting whole container into service is considered as a bad practice

Upvotes: 3

Related Questions