Antoine Nedelec
Antoine Nedelec

Reputation: 665

Symfony4 - Can't Autowire Service

It's the first time I try to autowire a service in symfony4, as symfony4 is new i'm never sure if the anwser I find online is working or is outdated..

In my services.yaml:

services:

   [...]

    smugmug_controller:
        class: App\Controller\SmugmugController
        arguments:
            - '@smugmug_service'

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones
    smugmug_service:
        class: App\Services\SmugmugService
        arguments:
            $consumerKey: "%smugmug.consumer_key%"
            $consumerSecret: "%smugmug.consumer_secret%"
            $oauthToken: "%smugmug.oauth_token%"
            $oauthTokenSecret: "%smugmug.oauth_token_secret%"
            $allowedRootId: "%smugmug.allowed_root_id%"

In my Smugmug Service:

class SmugmugService 
{
    private $consumerKey;
    private $consumerSecret;
    private $oauthToken;
    private $oauthTokenSecret;
    private $allowedRootId;
    private $galleryNameFromDropbox = "dropbox";

    /**
     * Constructor.
     *
     * @param string $consumerKey
     * @param string $consumerSecret
     * @param string $oauthToken
     * @param string $oauthTokenSecret
     * @param string $allowedRootId
     */
    public function __construct(String $consumerKey, String $consumerSecret, String $oauthToken, String $oauthTokenSecret, String $allowedRootId) {
        $this->consumerKey = $consumerKey;
        $this->consumerSecret = $consumerSecret;
        $this->oauthToken = $oauthToken;
        $this->oauthTokenSecret = $oauthTokenSecret;
        $this->allowedRootId = $allowedRootId;
    }

In my Controller:

class SmugmugController extends Controller {

    private $smugmugService;

    public function __construct(SmugmugService $smugmugService) {
        $this->smugmugService = $smugmugService;
    }

And when I try to call a route from my controller, I have this error:

Cannot autowire service "App\Services\SmugmugService": argument "$consumerKey" of method "__construct()" is type-hinted "string", you should configure its value explicitly.

I know that I call a controller with an injected service, who himself have injected parameters (is it the problem ?). Any help ?

Upvotes: 0

Views: 3756

Answers (1)

Antoine Nedelec
Antoine Nedelec

Reputation: 665

@Cerad answer:

You want to stop using service ids like smugmug_controller. Use the fully qualified class name instead. In fact if you replace the id with the class name then you can remove the class attribute. And anytime you look at an example, always make sure it is for S4 with autowire. It's all in the docs.

Upvotes: 3

Related Questions