这是容器感知服务的完整实现示例。
但请注意,应避免注入整个容器。最好只注入所需的组件。有关该主题的更多信息,请参阅得墨忒耳法则 - 维基百科。
为此,此命令将帮助您找到所有可用的服务:
# symfony < 3.0
php app/console debug:container
# symfony >= 3.0
php bin/console debug:container
无论如何,这是完整的示例。
app/config/services.yml
文件:
app.my_service:
class: AppBundle\Service\MyService
calls:
- [setContainer, ['@service_container']]
中的服务类src/AppBundle/Service/MyService.php
:
<?php
namespace AppBundle\Service;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
class MyService implements ContainerAwareInterface
{
use ContainerAwareTrait;
public function useTheContainer()
{
// do something with the container
$container = $this->container;
}
}
最后你的控制器在src/AppBundle/Controller/MyController.php
:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
/**
* My controller.
*/
class MyController extends Controller
{
/**
* @Route("/", name="app_index")
* @Method("GET")
*/
public function indexAction(Request $request)
{
$myService = $this->get('app.my_service');
$myService->useTheContainer();
return new Response();
}
}