首页 > 解决方案 > Symfony4 - 无法自动装配服务

问题描述

这是我第一次尝试在 symfony4 中自动连接服务,因为 symfony4 是新的,我永远不确定我在网上找到的 anwser 是工作还是过时..

在我的 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%"

在我的 Smugmug 服务中:

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;
    }

在我的控制器中:

class SmugmugController extends Controller {

    private $smugmugService;

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

当我尝试从控制器调用路由时,出现以下错误:

无法自动装配服务“App\Services\SmugmugService”:方法“__construct()”的参数“$consumerKey”是类型提示的“字符串”,您应该明确配置其值。

我知道我调用了一个带有注入服务的控制器,他自己已经注入了参数(这是问题吗?)。有什么帮助吗?

标签: phpsymfonyservicedependency-injectioncontroller

解决方案


@Cerad 答案:

您想停止使用像 smugmug_controller 这样的服务 ID。请改用完全限定的类名。实际上,如果您将 id 替换为类名,那么您可以删除类属性。每当您查看示例时,请始终确保它适用于具有自动装配功能的 S4。这一切都在文档中。


推荐阅读