简体   繁体   中英

Symfony 2 calling non-existent service “router”

I have a service MailController which is defined like this in my config

services:
    mail_controller:
        class: Company\Project\Bundle\Controller\MailController

I'm calling the Service in other services

$mailController = $this->get('mail_controller');

Now the error i get is building up on this Question

The container wasn't set on the Controller, so i'm injecting one within the constructor

// MailController    
public function __construct() {
    $this->setContainer(new Container());
}

Now i'm getting this error:

You have requested a non-existent service "router".

I'm guessing that i need to inject further services whatsoever, but i don't know what to inject, so what do i need to further add so my Controller can work with all services?

My MailController looks like this

namespace Company\Project\Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\Container;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Doctrine\ORM\EntityManager;

class MailController extends Controller{

    public function __construct() {
        $this->setContainer(new Container());
    }

    //Code for mailstuff

}

You're creating a new container rather than injecting the built container so it has no services.

To use your controller you need to inject the pre made service container in to your controller through your service like so..

services:
    mail_controller:
        class: Company\Project\Bundle\Controller\MailController
        calls:
            - [ setContainer, [ @service_container ]]

.. and get rid of the setter in your __construct .

injecting the whole service container

calls: - [ setContainer, [ @service_container ]]

defeats the purpose of declaring your controller as a service. Just inject the service(s) you need in your constructor. The constructor needs the service handed as an parameter and do not extend Controller anymore.

//MailController
use Symfony\Component\Routing\RouterInterface; 
class MailController
{
    private $router;

    public function __construct(RouterInterface $router){
        $this->router = $router;
    }

    //actions
}

Now you need to adjust your services.yml and extend the service with arguments describing the service you need

services:
    mail_controller:
        class: Company\Project\Bundle\Controller\MailController
        arguments:
           - @router

et voila, only one service needed, only one service injected. If you find yourself injecting too many services in one action, chances are your action/controller is not 'thin' enough.

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