thinkphpÖØд»ùÀàÒªÁì
ÔÚthinkphp5¿ò¼ÜÖУ¬»ùÀࣨbase£©ÊÇÒ»¸öºÜÊÇÖ÷ÒªµÄÀ࣬ËüÊÇËùÓпØÖÆÆ÷µÄ¸¸À࣬°üÀ¨ÁËÐí¶àÖ÷ÒªµÄÒªÁ죬ÀýÈ磺¿ØÖÆÆ÷³õʼ»¯¡¢Ä£°åäÖȾ¡¢Ä£°åÊä³öµÈµÈ¡£ÔÚÏÖʵ¿ª·¢ÖУ¬ÎÒÃÇÓÐʱÐèÒª¶Ô»ùÀàÖеÄijЩҪÁì¾ÙÐÐÖØд£¬ÒÔÖª×ã×Ô¼ºµÄÌض¨ÓªÒµÐèÇó¡£ÄÇô£¬ÔÚthinkphp5¿ò¼ÜÖУ¬ÔõÑùÖØд»ùÀàµÄÒªÁìÄØ£¿ÏÂÃæÎÒ½«ÏêϸÏÈÈÝ¡£
µÚÒ»²½£¬ÕÒµ½»ùÀàÎļþ
ÔÚThinkPHP5¿ò¼ÜÖУ¬»ùÀࣨBase£©ÎļþÔÚ¡°thinkController.php¡±ÖС£¸ÃÎļþµÄĬÈÏĿ¼ÊÇ¡°/thinkphp/library/think/¡±£¬Ò²¿ÉÒÔͨ¹ýcomposer×°Öõġ°topthink/framework¡±ÕÒµ½¸ÃÎļþ¡£Òò´Ë£¬ÎÒÃÇÐèÒªÏÈÕÒµ½¿ØÖÆÆ÷µÄ»ùÀàÎļþ£¬²Å»ª¶ÔÆä¾ÙÐÐÐ޸ġ£
µÚ¶þ²½£¬±àд×Ô½ç˵ҪÁì
ÔÚÖØд»ùÀàµÄÒªÁì֮ǰ£¬ÎÒÃÇÐèÒª±àд×Ô½ç˵µÄÒªÁì¡£Õâ¸öÒªÁìµÄ´úÂëÂß¼ÐèҪƾ֤ÏÖʵӪҵÐèÇóÀ´¾ÙÐбàд£¬¿ÉÒÔÔÚ¿ØÖÆÆ÷ÖÐÈκÎÐèÒªµÄλÖöÔÆä¾ÙÐÐŲÓ᣾ٸöÀý×Ó£¬ÎÒÃÇÐèÒªÔÚ¿ØÖÆÆ÷Êä³ö֮ǰ£¬ÏÈÅжÏÄ¿½ñÓû§ÊÇ·ñµÇ¼£¬ÈôÊÇÄ¿½ñÓû§Î´µÇ¼£¬ÔòÌøתÖÁµÇ¼ҳÃæ¡£
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
Ïêϸ²Ù×÷ÈçÏ£º
<?php namespace appindexcontroller; use thinkController; class Base extends Controller { public function _initialize() { parent::_initialize(); // ... } public function index() { // ... } public function checkLogin() { // ÅжÏÓû§ÊÇ·ñµÇ¼ if(!session('?user_id')) { $this->redirect('user/login'); } } }
µÇ¼ºó¸´ÖÆ
ÉÏÃæµÄʾÀý´úÂëÖУ¬ÎÒÃDZàдÁËÒ»¸öÃûΪ¡°checkLogin¡±µÄ×Ô½ç˵ҪÁ죬ÓÃÓÚÅжÏÓû§ÊÇ·ñµÇ¼¡£µ±Óû§Î´µÇ¼ʱ£¬¸ÃÒªÌå»áͨ¹ýredirectÒªÁìÌøתÖÁÖ¸¶¨µÄµÇ¼ҳÃæ¡£
µÚÈý²½£¬ÖØд»ùÀàÒªÁì
ÔÚ±àдÁË×Ô¼ºµÄ×Ô½ç˵ҪÁìÖ®ºó£¬ÎÒÃÇ¿ÉÒÔ¶Ô»ùÀàµÄÒªÁì¾ÙÐÐÖØд¡£ThinkPHP5¿ò¼ÜÖеĻùÀàÒªÁ춼ÊÇprotected»òpublicÀàÐ͵ÄÒªÁ죬ͨ³£¿ÉÒÔͨ¹ý¼ÌÐø»ùÀà¡¢ÖØд»ùÀàµÄÒªÁìÀ´ÊµÏÖ×Ô¼ºµÄÓªÒµÐèÇó¡£ÀýÈ磬ÎÒÃÇÐèÒªÔÚ¿ØÖÆÆ÷Êä³ö֮ǰ£¬ÅжÏÄ¿½ñÓû§ÊÇ·ñÒѾµÇ¼£¬ÈôÊÇÒѾµÇ¼£¬Ôò²»ÐèÒªÔÙ¾ÙÐÐÌøת¡£
Ïêϸ²Ù×÷ÈçÏ£º
<?php namespace appindexcontroller; use thinkController; class Base extends Controller { public function _initialize() { parent::_initialize(); $this->checkLogin(); // ŲÓÃ×Ô½ç˵ҪÁì¼ì²âÓû§ÊÇ·ñµÇ¼ } public function index() { // ... } // ÖØд»ùÀàµÄredirectÒªÁì protected function redirect($url, $params = array(), $code = 302, $with_prefix = false) { // Ä¿½ñÓû§ÒѵǼ£¬ÔòÖ±½ÓÊä³öÄ£°å if(session('?user_id')) { parent::redirect($url, $params, $code, $with_prefix); } // Ä¿½ñÓû§Î´µÇ¼£¬ÔòÌøתÖÁµÇ¼ҳÃæ else { parent::redirect('user/login'); } } }
µÇ¼ºó¸´ÖÆ
ÉÏÃæµÄʾÀý´úÂëÖУ¬ÎÒÃÇÖØдÁË»ùÀàµÄredirectÒªÁ죬ÓÃÓÚÅжÏÄ¿½ñÓû§ÊÇ·ñµÇ¼¡£µ±Óû§ÒѵǼʱ£¬Ôò»áÖ±½ÓÊä³öÄ£°å£»µ±Óû§Î´µÇ¼ʱ£¬Ôò»á×Ô¶¯ÌøתÖÁµÇ¼ҳÃæ¡£
×ܽá
ÔÚThinkPHP5¿ò¼ÜÖУ¬ÖØд»ùÀàµÄÒªÁì¿ÉÒÔ×ÊÖúÎÒÃÇʵÏÖ×Ô¼ºµÄÓªÒµÐèÇó¡£ÖØд»ùÀàµÄÒªÁìÐèÒª×ñÕÕ»ùÀàÒªÁìµÄÊðÃûºÍÓïÒ壬ͬʱÐèÒªÔÚÐÞ¸Ä֮ǰ¶Ô»ùÀàÒªÁìµÄʵÏÖ¾ÙÐÐ×ÐϸµÄÆÊÎö¡£ÖØд»ùÀàµÄÒªÁìÐèÒªÔÚ¿ØÖÆÆ÷ÖоÙÐУ¬Ïêϸ²Ù×÷°ì·¨°üÀ¨£ºÊ×Ïȱàд×Ô¼ºµÄ×Ô½ç˵ҪÁ죻ȻºóÖØд»ùÀàµÄÒªÁ죻×îºóÔÚÐèÒªµÄµØ·½Å²ÓÃ×Ô½ç˵ҪÁì¼´¿É¡£
ÒÔÉϾÍÊÇthinkphpÖØд»ùÀàÒªÁìµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡