thinkphpÔõôʵÏÖÊÖʱ»ú¼û²î±ð·¾¶
Ëæ×ÅÒƶ¯×°±¸µÄÆÕ¼°£¬»á¼ûÍøÕ¾µÄ·½·¨Ò²±äµÃ¶àÑù»¯¡£ÈôÊÇÄúʹÓõÄÊÇthinkphp¿ò¼Ü¿ª·¢ÍøÕ¾£¬²¢Ï£ÍûÔÚÒƶ¯×°±¸ÉÏ»á¼û²î±ðµÄ·¾¶£¬±¾ÆªÎÄÕ½«ÌṩһЩ×ÊÖú¡£
ThinkPHP¿ò¼ÜÖ§³Ö·Óɹ¦Ð§£¬Ê¹µÃ²î±ðµÄURL¿ÉÒÔÖ¸ÏòÏìÓ¦µÄ¿ØÖÆÆ÷ºÍ²Ù×÷ÒªÁ졣ͨ¹ýÕâÑùµÄ·½·¨£¬ÎÒÃÇ¿ÉÒÔÇáËɵØʵÏÖÊÖ»úºÍPC¶ËµÄ²î±ð»á¼û·¾¶¡£
Ê×ÏÈ£¬ÎÒÃÇÐèÒª½¨ÉèÒ»¸öÊÖʱ»ú¼ûµÄ·ÓɹæÔò¡£ÔÚThinkPHPÖУ¬¿ÉÒÔʹÓÃRouteÀàÀ´½ç˵·ÓɹæÔò¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔÔÚroute.phpÎļþÖÐÌí¼ÓÒÔÏ´úÂ룺
use think\facade\Route; Route::rule('/m/:controller/:action', '\app\mobile\controller\[:controller]\[:action]');
µÇ¼ºó¸´ÖÆ
Õâ¸ö·ÓɹæÔòÌåÏÖ£¬»á¼û¡°/m/¿ØÖÆÆ÷Ãû/²Ù×÷ÒªÁìÃû¡±Â·¾¶Ê±£¬½«»áŲÓÃapp\mobile\controller\¿ØÖÆÆ÷Ãû\²Ù×÷ÒªÁìÃû¿ØÖÆÆ÷µÄÒªÁì¡£
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒªÔÚmobileĿ¼Ï½¨ÉèÏìÓ¦µÄ¿ØÖÆÆ÷ÀàºÍ²Ù×÷ÒªÁì¡£ÀýÈ磬½¨ÉèÒ»¸öIndex¿ØÖÆÆ÷£¬²¢ÔÚÆäÖÐÌí¼ÓÒ»¸öhelloÒªÁ죺
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
namespace app\mobile\controller; class Index { public function hello() { return 'Hello, mobile world!'; } }
µÇ¼ºó¸´ÖÆ
ÏÖÔÚ£¬ÎÒÃÇ¿ÉÒÔÔÚÒƶ¯×°±¸ÉÏ»á¼û¡°/m/index/hello¡±Â·¾¶£¬¼´¿É¿´µ½¡°Hello, mobile world!¡±µÄÊä³ö¡£
ÈôÊÇÄúÏ£ÍûÔÚPC¶ËÒ²Äܹ»»á¼ûͬÑùµÄÁ´½Ó£¬¿ÉÒÔÔÚPC¶ËÔöÌíÒ»¸ö·ÓɹæÔò£¬ÈçÏÂËùʾ£º
use think\facade\Route; // PC¶Ë·ÓɹæÔò Route::rule('/:controller/:action', '\app\index\controller\[:controller]\[:action]'); // ÊÖ»ú¶Ë·ÓɹæÔò Route::rule('/m/:controller/:action', '\app\mobile\controller\[:controller]\[:action]');
µÇ¼ºó¸´ÖÆ
ÕâÑù£¬µ±»á¼û¡°/index/hello¡±Â·¾¶Ê±£¬Ò²»áŲÓÃIndex¿ØÖÆÆ÷µÄhelloÒªÁì¡£
³ýÁËʹÓ÷ÓɹæÔò£¬ÎÒÃÇ»¹¿ÉÒÔÔÚ¿ØÖÆÆ÷µÄ½á¹¹ÒªÁìÖÐÅжÏÓû§»á¼ûµÄ×°±¸ÀàÐÍ£¬ÔÙ¾ÙÐл®·Ö´¦Àí¡£ÀýÈ磺
namespace app\index\controller; class Index { public function __construct() { // ¼ì²âÓû§×°±¸ÀàÐÍ if ($this->isMobile()) { // ÊÖʱ»ú¼û $this->mobile(); } else { // PC»á¼û $this->pc(); } } protected function isMobile() { $agent = strtolower($_SERVER['HTTP_USER_AGENT']); $is_mobile = (strpos($agent, 'mobile') !== false) || (strpos($agent, 'android') !== false); return $is_mobile; } protected function mobile() { // ÊÖʱ»ú¼û´¦Àí echo 'Hello, mobile world!'; } protected function pc() { // PC»á¼û´¦Àí echo 'Hello, world!'; } }
µÇ¼ºó¸´ÖÆ
ÒÔÉÏ´úÂë»á¼ì²âÓû§µÄ×°±¸ÀàÐÍ£¬ÈôÊÇÊÇÒƶ¯×°±¸ÔòŲÓÃmobileÒªÁ죬²»È»Å²ÓÃpcÒªÁì¡£
ÐèҪעÖصÄÊÇ£¬ÉÏÊö´úÂëÖÐʹÓÃÁËPHPÄÚÖõÄ$_SERVER[‘HTTP_USER_AGENT’]±äÁ¿À´»ñÈ¡Óû§µÄ×°±¸ÀàÐÍ¡£ÕâÖÖ·½·¨ËäÈ»¼òÆÓ£¬µ«²¢²»·ó׼ȷ£¬ÓÉÓÚÕâ¸ö±äÁ¿¿ÉÒÔÓÉÓû§Î±Ôì¡£ÈôÊÇÐèÒª¸ü׼ȷµØÅжÏ×°±¸ÀàÐÍ£¬¿ÉÒÔʹÓõÚÈý·½¿â»òAPI£¬ÈçWURFL»òUser-Agent-API¡£
×ܽáÆðÀ´£¬ÒÔÉÏÊǼ¸ÖÖ³£¼ûµÄÔÚThinkPHPÖÐʵÏÖÊÖʱ»ú¼û²î±ð·¾¶µÄ·½·¨¡£Æ¾Ö¤ÏÖʵÐèÇ󣬿ÉÒÔÑ¡ÔñÊʺÏ×Ô¼ºµÄ·½·¨¡£Í¬Ê±£¬ÐèҪעÖر£»¤Óû§Òþ˽ºÍÌáÉýÓû§ÌåÑ飬ÀýÈç²»ÍøÂçÓû§Òþ˽£¬ÓÅ»¯Òƶ¯×°±¸»á¼ûËÙÂʵȡ£
ÒÔÉϾÍÊÇthinkphpÔõôʵÏÖÊÖʱ»ú¼û²î±ð·¾¶µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡