Search code examples
phpdoctrine-ormautowiredsymfony4doctrine-odm

Symfony4. ParamConverter annotation conflicts injecting a service by autowire


When I try to use @ParamConverter annotation in a Controller action, I get an error

"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."

I know that such a service does not exist, because I've excluded Document path in services.yaml. I just need to find a Company document object from Repostiroy.

Here is my controller code:

<?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 configuration:

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']

Solution

  • In case somebody else will get same problem. The problem had nothing to do with autowire conflict. @ParamConverter didn't work, because I used mongoDB and Doctrine ODM, not ORM. By default Doctrine ParamConverter won't work for mongo documents. So I found some information here https://matthiasnoback.nl/2012/10/symfony2-mongodb-odm-adding-the-missing-paramconverter/

    Define a new service in services.yaml file:

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

    Then @ParamConverter should work OK now.