Question

i have just implemented my first service in Symfony2.

I noticed that, within a controller method, whether i call the service so

$this->container->get('main.service');

or so

$this->get('main.service');

there is no difference.

I get the service equally with both.

Where are the differences?

Was it helpful?

Solution

There's no difference if you're extending the Base Controller provided by Symfony.

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class YourController extends Controller

If you take a deeper look at the implementation of the Symfony\Bundle\FrameworkBundle\Controller\Controller, you may notice that it provides a get() helper which do exactly the same call as what you did first (getting your service through the container).

So, then,

There's no difference as $this->get('something') simply sencapsulates a call to $this->container->get('something').


Here's the implementation of the get() method you're calling when doing $this->get('main.service');

/**
 * Gets a service by id.
 *
 * @param string $id The service id
 *
 * @return object The service
 */
public function get($id)
{
    return $this->container->get($id);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top