The method says it accepts objects whose class implements the interface ContainerInterface
. It doesn’t mean you’re getting an instance of an interface - that would be impossible.
In the case of the above code, you are receiving an instance of the class Container
(which in turn implements the interface ContainerInterface
). That’s why, from the container, you can get the service router
and thus generate the desired route.
Another thing: avoid injecting service containers into other services; prefer to inject individual services, so your code is cleaner and concise.
For example, if you want to inject only the service router
(which is the same argument when you use the method get
container), create your service definition as follows:
services:
api.response_factory:
class: AppBundle\Api\ResponseFactory
arguments: ['@router']
And then change the constructor to receive an object that implements the class RouterInterface
:
<?php
namespace AppBundle\Api;
use Symfony\Component\Routing\RouterInterface;
class ResponseFactory
{
/** @var RouterInterface $router */
protected $router;
/**
* @param RouterInterface $router
*/
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
}
You can see all the services available in your application (including the ones you created) through the command app/console container:debug
(or bin/console debug:container
in the case of Symfony 3 up).
Rodrigo, what do you mean, inject individual services? In my service I need to generate a route and I need the container for this, as would be a good practice for this?
– Filipe Moraes
I changed the answer to your question. :)
– Rodrigo Rigotti
I admire who shows using Symfony :D
– Wallace Maxters
@Wallacemaxters my favorite framework since forever :)
– Rodrigo Rigotti
@Wallacemaxters that was a compliment? kkk! Symfony is not solution to everything but serves very well for the projects I’m involved at the moment!
– Filipe Moraes
@Filipemoraes yes. The Framework is complex, but well done. Although I prefer the source code (the beauty of the code) of Laravel, I think that Symfony is very well structured. Even Laravel has a part that uses Symfony’s Httpfoundation. So whether I want to or not, I end up using Symfony :D
– Wallace Maxters