Symfony3实现刷新登录时间

在Symfony3中实现刷新登录时间、登录加1的功能需要自己写一个success handle。

简单讲一下创建success handle的流程,使用的环境如下
PHP版本:7.1.8
Symfony版本:3.3.5
默认管理员权限相关的Bundle名为AuthorizationBundle

首先我们在AuthorizationBundle下创建一个Service文件夹,用来储存所有与service相关的文件。建立一个AuthorizationHandle.php的文件,这个是我们用来实现success handle的代码文件。

因为实现success handle需要实现AuthenticationSuccessHandlerInterface接口中的方法,所以我们的handle类这么写

<?php

namespace HuanYue\AuthorizationBundle\Service;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;


class AuthorizationHandle implements AuthenticationSuccessHandlerInterface
{
    use ContainerAwareTrait;
    /**
     * This is called when an interactive authentication attempt succeeds. This
     * is called by authentication listeners inheriting from
     * AbstractAuthenticationListener.
     *
     * @param Request        $request
     * @param TokenInterface $token
     *
     * @return Response never null
     */
    function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        $user = $token->getUser();
        $user->setLastLogin(new \DateTime());
        $user->save();

        return new RedirectResponse($this->container->get('router')->generate('huan_yue_admin_authorization_dashboard'));
    }
}

下面解释一下代码,AuthenticationSuccessHandlerInterface中的注释很清晰的写明了我们可以在onAuthenticationSuccess中实现我们的功能,并且最后需要返回一个Response。我们进行刷新登录时间、或者登录加1、或者其他什么操作后需要跳转到后台首页,因此需要生成一个RedirectResponse,我的代码里用到了Symfony container去获取router,所以需要使用Symfony提供给我们的Trait(注:在2.*版本中可以直接继承ContainerAware类)。到此,我们的success handel已经实现完成。

下一步,我们把我们的AuthorizationHandle注册到Symfony的Service中,在Resources\services.yml中添加

services:

huan_yue_authorization.authorization_handle:
    class: HuanYue\AuthorizationBundle\Service\AuthorizationHandle
    calls:
        - [ setContainer, [ "@service_container" ] ]

最后一步,修改app\config\security.yml文件,在form_login下添加我们的success handle,代码如下

form_login:
    check_path: huan_yue_admin_authorization_login
    login_path: huan_yue_admin_authorization_login
    default_target_path: huan_yue_admin_authorization_dashboard
    success_handler: huan_yue_authorization.authorization_handle

到此,整个流程完成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值