Reputation: 4766
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
}
Upvotes: 0
Views: 741
Reputation: 11
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.
Upvotes: 1
Reputation: 17759
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
.
Upvotes: 1