symfony - 用户登录后调用方法

标签 symfony fosuserbundle

我想知道用户登录后是否可以调用函数。

这是我要调用的代码:

$point = $this->container->get('process_points');
$point->ProcessPoints(1 , $this->container);

最佳答案

您可以在 FOSUserEvents class 中找到 FOSUserBundle 触发的事件。更具体地说,这就是您正在寻找的:

/**
 * The SECURITY_IMPLICIT_LOGIN event occurs when the user is logged in programmatically.
 *
 * This event allows you to access the response which will be sent.
 * The event listener method receives a FOS\UserBundle\Event\UserEvent instance.
 */
const SECURITY_IMPLICIT_LOGIN = 'fos_user.security.implicit_login';

用于 Hook 这些事件的文档可以在 Hooking into the controllers 上找到。文档页面。在您的情况下,您将需要实现如下所示的内容:

namespace Acme\UserBundle\EventListener;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

/**
 * Listener responsible to change the redirection at the end of the password resetting
 */
class LoginListener implements EventSubscriberInterface
{
    private $container;

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

    /**
     * {@inheritDoc}
     */
    public static function getSubscribedEvents()
    {
        return array(
            FOSUserEvents::SECURITY_IMPLICIT_LOGIN => 'onLogin',
            SecurityEvents::INTERACTIVE_LOGIN => 'onLogin',
        );
    }

    public function onLogin($event)
    {
        // FYI
        // if ($event instanceof UserEvent) {
        //    $user = $event->getUser();
        // }
        // if ($event instanceof InteractiveLoginEvent) {
        //    $user = $event->getAuthenticationToken()->getUser();
        // }

        $point = $this->container->get('process_points');
        $point->ProcessPoints(1 , $this->container);
    }
}

然后,您应该将监听器定义为服务并注入(inject)容器。或者,您可以只注入(inject)您需要的服务,而不是整个容器。

services:
    acme_user.login:
        class: Acme\UserBundle\EventListener\LoginListener
        arguments: [@container]
        tags:
            - { name: kernel.event_subscriber }

还有另一种方法涉及 overriding the controller ,但正如文档中所述,您必须复制他们的代码,因此它并不完全干净,并且如果(或者更确切地说,当)FOSUserBundle 更改时必然会中断。

关于symfony - 用户登录后调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17055721/

相关文章:

php - Symfony MessageHandler 计算一条消息被发送了多少次

symfony - 交响乐 3.4 : FOS User Bundle : Override Controller

symfony - FOS用户包 : no route found for Security:Login

symfony - 使用 Bootstrap 自定义 FOSUserBundle 登录模板

php - Symfony2 - 如何在 Controller 中验证电子邮件地址

symfony - Doctrine DQL 从关系表中删除

mysql - 查询构建器选择实体关系 ID

php - Symfony.4 Sonata AdminBundle 注销错误 : You must activate the logout in your security firewall configuration

Symfony 2.2.1 远程服务器上出现 fatal error (仅限)-为什么?

php - 具有多个具有相同名称的查询字符串参数的 Symfony HttpClient GET 请求