gpt4 book ai didi

symfony - Symfony2 Controller 中的构造函数

转载 作者:行者123 更新时间:2023-12-02 11:58:04 24 4
gpt4 key购买 nike

如何在 Symfony2 Controller 中定义构造函数。我想在 Controller 的所有方法中获取已登录的用户数据,目前我在 Controller 的每个操作中都执行类似的操作来获取已登录的用户。

$em = $this->getDoctrine()->getEntityManager("pp_userdata");
$user = $this->get("security.context")->getToken()->getUser();

我想在构造函数中执行一次,并使该登录用户可用于我的所有操作

最佳答案

对于在每个 Controller 操作之前执行代码的通用解决方案,您可以将事件监听器附加到 kernel.controller 事件,如下所示:

<service id="your_app.listener.before_controller" class="App\CoreBundle\EventListener\BeforeControllerListener" scope="request">
<tag name="kernel.event_listener" event="kernel.controller" method="onKernelController"/>
<argument type="service" id="security.context"/>
</service>

然后在您的 BeforeControllerListener 中,您将检查 Controller 以查看它是否实现了接口(interface),如果实现了,您将从接口(interface)调用方法并传入安全上下文。

<?php

namespace App\CoreBundle\EventListener;

use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\Security\Core\SecurityContextInterface;
use App\CoreBundle\Model\InitializableControllerInterface;

/**
* @author Matt Drollette <matt@drollette.com>
*/
class BeforeControllerListener
{

protected $security_context;

public function __construct(SecurityContextInterface $security_context)
{
$this->security_context = $security_context;
}

public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();

if (!is_array($controller)) {
// not a object but a different kind of callable. Do nothing
return;
}

$controllerObject = $controller[0];

// skip initializing for exceptions
if ($controllerObject instanceof ExceptionController) {
return;
}

if ($controllerObject instanceof InitializableControllerInterface) {
// this method is the one that is part of the interface.
$controllerObject->initialize($event->getRequest(), $this->security_context);
}
}
}

然后,任何您希望用户始终可用的 Controller 都只需实现该接口(interface)并设置用户,如下所示:

use App\CoreBundle\Model\InitializableControllerInterface;

class DefaultController implements InitializableControllerInterface
{
/**
* Current user.
*
* @var User
*/
private $user;

/**
* {@inheritdoc}
*/
public function initialize(Request $request, SecurityContextInterface $security_context)
{
$this->user = $security_context->getToken()->getUser();
}
// ....
}

界面无非

namespace App\CoreBundle\Model;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContextInterface;

interface InitializableControllerInterface
{
public function initialize(Request $request, SecurityContextInterface $security_context);
}

关于symfony - Symfony2 Controller 中的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11179191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com