6

I want to set an alias for a service in order to be able to use different services in different environments. So, here is the services.yaml

.
.
.
register_request:
        alias: %register_request_service%
main_register_request:
        class: AppBundle\Services\Requests\RegisterRequest
null_register_request:
        class: AppBundle\Services\Requests\NullRegisterRequest
.
.
.

and in my development environment the parameters.yml looks like:

.
.
.
    register_request_service: null_register_request
.
.
.

But it does not work! when I use clear:cache it says:

  [Symfony\Component\DependencyInjection\Exception\InvalidArgumentException]
  Unable to replace alias "%register_request_service%" with "register_request".

  [Symfony\Component\DependencyInjection\Exception\InvalidArgumentException]
  The service definition "%register_request_service%" does not exist.

Any Idea about what I'm missing?

A.Alinia
  • 624
  • 6
  • 12

2 Answers2

3

Elnur answer works but I decided to fix the problem this way:

I have created a services config file for dev environment (services_dev.yml) and did override the service in it. So, the services.yml looks like:

# app/config/services.yml
# ...
services:
    # ...
    register_request:
            class: AppBundle\Services\Requests\RegisterRequest
    # ...

and the services_dev.yml looks like:

# app/config/services_dev.yml
services:
    register_request:
            class: AppBundle\Services\Requests\NullRegisterRequest

Then, I have imported the services_dev.yml in in config_dev.yml

# app/config/config_dev.yml
imports:
    - { resource: config.yml }
    - { resource: services_dev.yml }

# ...

This way the application setup process does not need the extra information about those classes' name.

A.Alinia
  • 624
  • 6
  • 12
2

It's easier to just define the class name as a parameter. That's the idiom used a lot in Symfony itself and its bundles.

Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
  • I agree with Alireza's answer. In the best practices document, it says that "Don't define parameters for the classes of your services." While I agree that you shouldn't follow any document blindly to the tee, having environment-based services means someone installing your web application doesn't constantly have to define a value in `parameters.yml`. – Parham Doustdar Jan 16 '16 at 09:26
  • Did I say anything about `parameters.yml`? – Elnur Abdurrakhimov Jan 16 '16 at 10:38
  • Nope. You said nothing about where to define parameters, and the usual place for defining parameters is in the file that is named after them. Your answer is only one paragraph so I have to guess most of what you mean; sorry if my guesses fall short. – Parham Doustdar Jan 17 '16 at 05:49