Symfony 4 dependecy injection – Define constructor arguments depending on use case [duplicate]

  dependency-injection, php, symfony, symfony4

I have a generic service who uses a configuration to do its processing.

<?php

namespace AppService;

class MyCustomService
{
    /**
     * @var array
     */
    private $config;

    /**
     * MyCustomService constructor.
     *
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->config = $config;
    }

    public function getConfig()
    {
        return $this->config;
    }
}

I want to inject that service in my controller’s actions. But with a specific configuration for each action.

<?php

namespace AppController;

use AppServiceMyCustomService;

class MyCustomController
{
    public function action_1(MyCustomService $myCustomService)
    {
        /**
         * $config must contain 
         * ['foo' => 'bar']
         */
        $config = $myCustomService->getConfig();
    }

    public function action_2(MyCustomService $myCustomService)
    {
        /**
         * $config must contain
         * ['foo' => 'baz']
         */
        $config = $myCustomService->getConfig();
    }
}

How can I do that using config/services. Yaml?

Is there a way to configure a controller action?

Like this, for example:

services: 
    #...
    #...
    #...
        
    AppControllerMyCustomController:action_1:
        arguments:
            $myCustomService: 
                AppServiceMyCustomService:
                    arguments:
                        $config: {foo: 'bar'}
        
    AppControllerMyCustomController:action_2:
        arguments:
            $myCustomService: 
                AppServiceMyCustomService:
                    arguments:
                        $config: {foo: 'baz'}

I could use a config method inside MyCustomService, and call it inside every controller’s action. But it’s not that elegant.

Source: Ask PHP

LEAVE A COMMENT