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類這么寫
<?phpnamespace 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\AuthorizationHandlecalls:- [ setContainer, [ "@service_container" ] ]最后一步,修改app\config\security.yml文件,在form_login下添加我們的success handle,代碼如下
form_login:check_path: huan_yue_admin_authorization_loginlogin_path: huan_yue_admin_authorization_logindefault_target_path: huan_yue_admin_authorization_dashboardsuccess_handler: huan_yue_authorization.authorization_handle到此,整個流程完成。
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Symfony3实现刷新登录时间的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python中的内存管理机制
- 下一篇: Window2008R2安装Telnet