San*_*nti 10 bundle listener symfony doctrine-orm
我们需要在侦听器中访问数据库信息.我们在service.yml中配置监听器.监听器如下:
namespace company\MyBundle\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class RequestListener
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function onKernelRequest(GetResponseEvent $event)
{
...
Run Code Online (Sandbox Code Playgroud)
我们如何在onKernelRequest函数中访问doctrine?
我试图从控制器扩展并做:
$em = $this->getDoctrine()->getEntityManager();
Run Code Online (Sandbox Code Playgroud)
它有效,但我认为这是一个不好的做法.
sol*_*arc 28
您可以注入服务容器.首先更改构造函数以获取EntityManager:
use Doctrine\ORM\EntityManager;
class RequestListener {
protected $em;
function __construct(EntityManager $em)
{
$this->em = $em;
}
//...
}
Run Code Online (Sandbox Code Playgroud)
然后配置您的服务:
#...
services:
foo.requestlistener:
class: %foo.requestlistener.class%
arguments:
- @doctrine.orm.entity_manager
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13016 次 |
| 最近记录: |