Unnikrishnan
Unnikrishnan

Reputation: 3353

Using Symfony2 service definitions in Symfony4, with multiple services for the same class

I have the following service definition in Symfony2

app.service_1:
   class: Symfony\Component\Lock\Store\RedisStore
   arguments:
       - '@snc_redis.default_cache'

app.service_2:
    class: Symfony\Component\Lock\Store\RedisStore
    arguments:
        - '@snc_redis.scheduler_cache'

Now I'm planning to upgrade to Symnfony4 where I need to give classpath as the service name

Symfony\Component\Lock\Store\RedisStore
   arguments:
       - '@snc_redis.default_cache'

Symfony\Component\Lock\Store\RedisStore
    arguments:
        - '@snc_redis.scheduler_cache'

Here the problem is it has the same name because we use the same classpath? How I can fix it? Can I use an alias with different parameters?

Upvotes: 1

Views: 301

Answers (2)

yivi
yivi

Reputation: 47639

You do not need to change the definition.

When you need to create several services from the same class, using the FQCN as an identifier won't work. Using the fully qualified class name is recommended and a good practice, but it's not mandatory. It's practical most of the time, since you can omit the class argument, and you do not need to pick a name for each service.

Your original definition is perfectly compatible with Symfony 4 (or 5):

app.service_1:
   class: Symfony\Component\Lock\Store\RedisStore
   arguments:
       - '@snc_redis.default_cache'

app.service_2:
    class: Symfony\Component\Lock\Store\RedisStore
    arguments:
        - '@snc_redis.scheduler_cache'

I would simply advise to use more descriptive identifiers than service_1 and service_2.

Upvotes: 1

Astro-Otter
Astro-Otter

Reputation: 873

An other way is to use alias like explain in documentation

services:
  Symfony\Component\Lock\Store\RedisStore:
    public: false
    arguments:
      - '@snc_redis.default_cache'

  app.service_1:
    alias: Symfony\Component\Lock\Store\RedisStore
    public: true

  Symfony\Component\Lock\Store\RedisStore:
    arguments:
      - '@snc_redis.scheduler_cache'
  app.service_2:
    alias: Symfony\Component\Lock\Store\RedisStore
    public: true

You can also use bind and autowire: true for your arguments. But your variables in services.yml must be same as them declared in constructor of yours services. Look something like this:

services:
  # default configuration for services in *this* file
  _defaults:
    autowire: true      
    autoconfigure: true
    bind:
      $defaultCache: '@snc_redis.default_cache'
      $schedulerCache: '@snc_redis.scheduler_cache'

    Symfony\Component\Lock\Store\RedisStore:
      public: false

(or use bind only in your service declaration).

PS: caution in your example, you miss : after class path :)

Upvotes: -1

Related Questions