首页 > 解决方案 > symfony 中的 Autowire 字符串参数

问题描述

如何在 Symfony 3.4 中连接字符串参数?

我有简单的服务,我想连接一个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;
    }
}

我的service.yml样子:

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

但我收到错误:

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

我也试过手动指定参数:

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

这给了我以下错误:

Invalid service "AppBundle\Services\PythonService": class "AppBundle\Services\PythonService" does not exist.

标签: phpsymfony

解决方案


AppBundle\Services\PythonService首先,您在(Services <> Service)中有错字。

然后,字符串 <> 字符串。php中没有大写。


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

服务.yml:

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

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

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

控制器动作:

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

使用此解决方案,如果您创建其他需要 的服务memecacheHostUri,它也会为这些服务自动装配。

资源:

参数绑定


推荐阅读