有人可以幫助我從event.controller中獲取事件監聽器中的用戶ID嗎?Symfony2在kernel.controller事件監聽器上獲取userID
# EventListener
kernel.listener.corporation.manage:
class: Site\CorporationBundle\Event\SiteCorporationManageListener
arguments: ["@doctrine.orm.entity_manager", "@user.own.item", "@security.context"]
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelRequest }
和監聽類
use Doctrine\ORM\EntityManager;
use Site\MainBundle\Service\UserOwnItem;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\SecurityContext;
class SiteCorporationManageListener
{
private $oEntityManager = null;
private $oUserOwnItem = null;
private $oSecurityContext = null;
public function __construct(EntityManager $oEntityManager, UserOwnItem $oUserOwnItem, SecurityContext $oSecurityContext)
{
$this->oEntityManager = $oEntityManager;
$this->oUserOwnItem = $oUserOwnItem;
$this->oSecurityContext = $oSecurityContext;
}
public function onKernelRequest(FilterControllerEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
$route = $event->getRequest()->get('_route');
$corporationID = $event->getRequest()->get('corporationID', null);
$userID = $this->oSecurityContext->getToken()->getUser()->getID();
//$userID = 3;
//var_dump($userID);
if (strstr($route, 'corporation')) {
if (!strstr($route, 'corporation_index')) {
$bUserOwn = $this->oUserOwnItem->setUserID($userID)->setItemType('corporation')->setItemID($corporationID)->userOwn();
//var_dump($bUserOwn);
}
}
}
}
}
以後我會清掃它,我嘗試不同的方法來做到這一點,但即使通過容器和security_context我不能得到用戶ID。它在getToken()方法=之後中斷。
在這個例子$用戶ID是空...即使在爲gettoken() - >的getUser()給我空...
FatalErrorException: Error: Call to a member function getUser() on a non-object in /home/dev/public_html/git.eve-ceo/src/Site/CorporationBundle/Event/SiteCorporationManageListener.php line 32
請幫助。
我不認爲$ context-> getToken() - > getUser()!=='anon。'是非常好的選擇。 – user1954544