Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowire String parameter in symfony

Tags:

php

symfony

How can I wire a String parameter in Symfony 3.4?

I have simple service and I want to wire a url parameter specified in parameters.yml:

namespace AppBundle\Service;

use Psr\Log\LoggerInterface;

class PythonService {

    private $logger;
    private $url;

    /**
     * @param LoggerInterface $logger
     * @param String $url
     */
    public function __construct(LoggerInterface $logger, String $url) {
        $this->logger = $logger;
        $this->url = $url;
    }
}

My service.yml looks like:

AppBunde\Services\PythonService:
    arguments: ['@logger', '%url%']

But I am getting error:

Cannot autowire service "AppBundle\Service\PythonService": argument "$url" of method "__construct()" is type-hinted "string", you should configure its value explicitly.

I tried also manually specify parameters:

AnalyticsDashboardBunde\Services\PythonService:
    arguments:
        $logger: '@logger'
        $url: '%session_memcached_host%'

This gives me following error:

Invalid service "AppBundle\Services\PythonService": class "AppBundle\Services\PythonService" does not exist.
like image 998
Joozty Avatar asked Aug 03 '18 12:08

Joozty


People also ask

What is Autowire PHP?

Autowiring is an exotic word that represents something very simple: the ability of the container to automatically create and inject dependencies. In order to achieve that, PHP-DI uses PHP's reflection to detect what parameters a constructor needs. Autowiring does not affect performances when compiling the container.

What is container Symfony?

In Symfony, these useful objects are called services and each service lives inside a very special object called the service container. The container allows you to centralize the way objects are constructed. It makes your life easier, promotes a strong architecture and is super fast!


1 Answers

First, you have a typo in AppBundle\Services\PythonService (Services <> Service).

Then, string <> String. No uppercase in php.


You can bind an argument to a certain parameter/service:

service.yml:

services:
    _defaults:
        bind:
            $memcacheHostUri: '%session_memcached_host%'

Service class: (have to be the same var name as specified ^)

public function __construct(LoggerInterface $logger, string $memcacheHostUri)

Controller action:

public function myAwesomeAction(PythonService $pythonService)
{
    $pythonService->doPythonStuffs();
}

With this solution, if you create others services which need the memecacheHostUri, it will be autowired for these services too.

Resources:

Argument binding

like image 128
G1.3 Avatar answered Sep 30 '22 03:09

G1.3