In the controller, I could do
$this->get(\'service.name\')
But in a custom class, how can I do that?
If you do not know the full list of dependencies that you need at the moment when the service is created, you can pass the container as the argument http://symfony.com/doc/current/book/service_container.html#using-the-expression-language
services:
service_name:
class: AppBundle\Class
arguments: ['@=container']
Define your custom class as a service, and then inject dependencies into it.
Ex:
// services.yml
services:
my.custom.service.id:
class: My\Custom\Class
arguments:
- @service.name
- @doctrine.orm.entity_manager
Your custom class' constructor would then get those services as arguments.
Be sure to read up on the Service Container in the official docs. It goes over all this in great detail.
This is not best practice to do, but it works. If your custom class is not set to be a service then you can access the service container using global variable $kernel:
class Helper {
private $container;
/**
* Constructor assigns service container to private container.
*/
public function __construct() {
global $kernel;
$this->container = $kernel->getContainer();
}
function doSOmething() {
$someService = $this->container->get('service.name');
// do something with someService ...
}
}
You were on the right track with ContainerAware.
$this->get('id')
is actually a shortcut to $this->container->get('id')
. And getting container into your class is as simple as implementing ContainerAwareInterface
- putting this snippet into your class:
public function setContainer(\Symfony\Component\DependencyInjection\ContainerInterface $container = null)
{
$this->container = $container;
}
OK I suppose @Arms answer is a possible solution, I found by looking at the source to Controller
, I could extend ContainerAware