symfony中的Autowire String参数

Joo*_*zty 3 php symfony

如何在Symfony 3.4中连接String参数?

我有简单的服务,我想连接一个url指定的参数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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我service.yml看起来像:

AppBunde\Services\PythonService:
    arguments: ['@logger', '%url%']
Run Code Online (Sandbox Code Playgroud)

但我收到错误:

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

我也试过手动指定参数:

AnalyticsDashboardBunde\Services\PythonService:
    arguments:
        $logger: '@logger'
        $url: '%session_memcached_host%'
Run Code Online (Sandbox Code Playgroud)

这给了我以下错误:

Invalid service "AppBundle\Services\PythonService": class "AppBundle\Services\PythonService" does not exist.
Run Code Online (Sandbox Code Playgroud)

G1.*_*1.3 8

首先,你有一个拼写错误AppBundle\Services\PythonService(服务<>服务).

然后,string <> String.在PHP中没有大写.


您可以将参数绑定到某个参数/服务:

service.yml:

services:
    _defaults:
        bind:
            $memcacheHostUri: '%session_memcached_host%'
Run Code Online (Sandbox Code Playgroud)

服务类:(必须与指定的^名称相同)

public function __construct(LoggerInterface $logger, string $memcacheHostUri)
Run Code Online (Sandbox Code Playgroud)

控制器动作:

public function myAwesomeAction(PythonService $pythonService)
{
    $pythonService->doPythonStuffs();
}
Run Code Online (Sandbox Code Playgroud)

使用此解决方案,如果您创建其他需要的服务memecacheHostUri,它也将自动连接这些服务.

资源:

参数绑定