7

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

这是我要调用的代码:

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

1 回答 1

28

您可以在FOSUserEvents 类中找到 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';

挂钩这些事件的文档可以在挂钩到控制器文档页面上找到。在您的情况下,您将需要实现以下内容:

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 }

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

于 2013-06-12T02:25:05.053 回答