简体   繁体   中英

Symfony FOSRestController as a service (Dependency injection)

I'm trying to use dependency injection in my controller. I'm using FOSRestController.

I received an error :

Bundle "app.person_rest_controller" does not exist or it is not enabled. Maybe you forgot to add it in the registerBundles() method of your AppKernel.php file? in /var/www/html/src/AppBundle/Resources/config/routing.yml (which is being imported from "/var/www/html/app/config/routing.yml").

My Controller looks like :

class PersonRestController extends FOSRestController
{

    private $entityManager;
    private $container;
    private $sendNewContactRabbitMQProducer;

    public function __construct(EntityManager $entityManager, $container, Producer $rabbitMQProducer)
    {
        $this->entityManager = $entityManager;
        $this->container = $container;
        $this->sendNewContactRabbitMQProducer = $rabbitMQProducer;
    }

    public function postPersonAction(ParamFetcher $paramFetcher)
    {
        ...
    }

My routing.yml :

service_person:
    type: rest
    prefix: /v1
    resource: "@app.person_rest_controller"
    name_prefix:  api_1_ # naming collision

And my services.yml :

services:
    app.person_rest_controller:
        class: AppBundle\Controller\PersonRestController
        arguments:
            - "@doctrine.orm.entity_manager"
            - "@service_container"
            - "@person.rabbitmq.producer.send_new_contact"
    person.rabbitmq.producer.send_new_contact:
        class: AppBundle\Service\SendNewContactRabbitMQProducer
        arguments: []
        calls:
            - [setRabbitMQProducer, ["@old_sound_rabbit_mq.send_person_id_from_hotelpro4u_producer"]]
            - [setLogger, ['@logger']]

I base my work on this : https://github.com/FriendsOfSymfony/FOSRestBundle/issues/990

An idea ?

Thank you ! =)

Two quick things, especially since you seem to have an error message that actually helps you:

  1. You need to install the FosRESTBundle via composer
  2. You need to enable it in you AppKernel.php

Both of these are explained on the official Symfony documentation .
Generally, you find the AppKernel.php under /symfony/project/root/doc/app/AppKernel.php

I founded the solution, it's was a stupid error :

The service controller don't have a @ before the name.

Change :

service_person:
    type: rest
    prefix: /v1
    resource: "@app.person_rest_controller"
    name_prefix:  api_1_ # naming collision

to this :

service_person:
    type: rest
    prefix: /v1
    resource: "app.person_rest_controller"
    name_prefix:  api_1_ # naming collision

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM