Symfony 2 service container is null
php, symfony
Solution
//services.yml
service:
myname_googleapi_youtube:
class: Myname\GoogleApiBundle\Controller\YouTubeController
arguments: [@service_container]
And you would have:
<?php
namespace Myname\GoogleApiBundle\Controller
use Symfony\Component\DependencyInjection\ContainerInterface;
class YouTubeController
{
/**
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* Obtain some results
*/
public function getResultFunction()
{
$parameter = $this->container->getParameter('a');
//...
}
/**
* Get a service from the container
*
* @param string The service to get
*/
protected function get($service)
{
return $this->container->get($service);
}
}
This practice is very controversial, so I'd recommend that you have a quick read at these:
- Controllers as Services in Symfony2
- Do you want DIC with that Controller?
- Symfony2: Make my Controllers Services?
Problem
I am new to Symfony 2 and trying to create some simple application to learn. I created a bundle `GoogleApiBundle`. Inside the bundle, I have a controller `YouTubeController`, which is a service: ``` //services.yml service: myname_googleapi_youtube: class: Myname\GoogleApiBundle\Controller\YouTubeController ``` In another bundle, I try to call a function in `YouTubeController` ``` //anotherController.php $service = $this->get('myname_googleapi_youtube'); $result = $service->getResultFunction(); //YouTubeController.php public function getResultFunction() { $parameter = $this->container->getParameter('a'); //... } ``` Then I get an exception `FatalErrorException: Error: Call to a member function getParameter() on a non-object ...`, because `$this->container` is `NULL`. I searched but didn't get an answer. Am I doing wrong?