簡體   English   中英

Symfony4。 ParamConverter注釋與通過autowire注入服務沖突

[英]Symfony4. ParamConverter annotation conflicts injecting a service by autowire

當我嘗試在Controller動作中使用@ParamConverter注釋時,我收到一個錯誤

"Cannot resolve argument $company of \"App\\Controller\\ProfileController::top()\": Cannot autowire service \".service_locator.0CrkHeS\": it references class \"App\\Document\\Company\" but no such service exists."

我知道這樣的服務不存在,因為我已經在services.yaml排除了Document path。 我只需要從Repostiroy找到一個公司文檔對象。

這是我的控制器代碼:

<?php

// src/Controller/ProfileController.php
namespace App\Controller;

use App\Document\Company;
use App\Service\DocumentManager\CompanyManager;
use FOS\RestBundle\Controller\FOSRestController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Swagger\Annotations as SWG;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/profile")
 */
class ProfileController extends FOSRestController
{
    /**
     * @Route("/top/{id}")
     * @Method("GET")
     * @SWG\Response(
     *     response=200,
     *     description="Returns top profiles",
     * )
     * @SWG\Tag(name="profile")
     *
     * @ParamConverter("company", class="App\Document\Company")
     * @param CompanyManager $companyManager
     * @return Response
     */
    public function top(CompanyManager $companyManager, Company $company)
    {
        dump($company->getId());exit;
        return $this->handleView($this->view($companyManager->getTopProfiles(), Response::HTTP_OK));
    }

}

services.yaml配置:

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false

    App\:
        resource: '../src/*'
        exclude: '../src/{Entity,Document,Migrations,Tests,Kernel.php,Exception,DataFixtures}'

    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

萬一其他人會遇到同樣的問題。 這個問題與autowire沖突無關。 @ParamConverter不起作用,因為我使用的是mongoDB和Doctrine ODM,而不是ORM。 默認情況下,Doctrine ParamConverter不適用於mongo文檔。 所以我在這里找到了一些信息https://matthiasnoback.nl/2012/10/symfony2-mongodb-odm-adding-the-missing-paramconverter/

services.yaml文件中定義新服務:

doctrine_mongo_db_param_converter:
    class: Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DoctrineParamConverter
    tags:
        - { name: request.param_converter, converter: doctrine.odm }
    arguments: ['@doctrine_mongodb']

那么@ParamConverter現在應該可以正常工作了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM