用户登录后调用方法

2024-03-16

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

这是我要调用的代码:

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

您可以在中找到 FOSUserBundle 触发的事件FOSUserEvents 类 https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/FOSUserEvents.php。更具体地说,这就是您正在寻找的:

/**
 * 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';

用于挂钩这些事件的文档可以在连接到控制器 https://symfony.com/doc/master/bundles/FOSUserBundle/controller_events.html文档页面。在你的情况下,你需要实现这样的事情:

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);
    }
}

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

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

还有另一种方法涉及覆盖控制器 https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/overriding_controllers.rst,但正如文档中所述,您必须复制他们的代码,因此它并不完全干净,并且如果(或者更确切地说,当)FOSUserBundle 更改时必然会中断。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用户登录后调用方法 的相关文章

随机推荐