laravel ÅжÏÊÇ·ñcli
laravel ÊÇÏÖ´ú php ¿ª·¢ÖеÄÈÈÃÅ¿ò¼ÜÖ®Ò»£¬ÆÕ±éÓ¦ÓÃÓÚ web Ó¦ÓóÌÐò¿ª·¢ºÍ api ¿ª·¢¡£ÔÚ laravel µÄÓ¦ÓóÌÐò¿ª·¢ÖУ¬ÎÒÃÇÐèÒª¾³£ÅжϳÌÐòÊÇÔÚÏÂÁîÐÐģʽÏÂÔËÐÐÕÕ¾ÉÔÚ web ģʽÏÂÔËÐУ¬ÒÔ±ãÓ¦¶Ô²î±ðµÄÓ¦Óó¡¾°¡£
ÅÐ¶Ï Laravel ÊÇ·ñÔÚÏÂÁîÐÐģʽÏÂÔËÐÐÊǺܳ£¼ûµÄ²Ù×÷¡£ÀýÈ磬ÎÒÃÇ¿ÉÄÜÐèÒªÔÚ CLI ÖÐÖ´ÐÐÍýÏëʹÃü¡¢´¦Àí´ó×ÚµÄÊý¾Ý¡¢ÌìÉúÎļþ¡¢¶ÔÊý¾Ý¿â¾ÙÐÐǨáãµÈµÈ¡£¶øÔÚ Web ģʽÏ£¬ÔòÐèÒª´¦Àí HTTP ÇëÇóºÍÏìÓ¦¡¢¾ÙÐÐÓû§Éí·ÝÈÏÖ¤¡¢Ê¹ÓÃÇ°¶Ë¿ò¼ÜµÈµÈ¡£Òò´Ë£¬×¼È·µÄÅÐ¶Ï Laravel ÕýÔÚÔËÐеÄģʽ£¬¹ØÓÚÎÒÃÇʵÏÖÔ½·¢ÓÐÓú͸ßЧµÄÓ¦ÓóÌÐòÖÁ¹ØÖ÷Òª¡£
ÔÚ Laravel ÖУ¬ÎÒÃÇ¿ÉÒÔͨ¹ý¼ì²é PHP ³£Á¿ PHP_SAPI À´ÅжÏÓ¦ÓóÌÐòµÄÔËÐÐģʽ¡£Õâ¸ö³£Á¿µÄÖµÌåÏÖÄ¿½ñ PHP ³ÌÐòÕýÔÚʹÓÃµÄ SAPI£¨Server Application Programming Interface£¬¼´Ð§ÀÍÆ÷¶ËÓ¦ÓóÌÐò±à³Ì½Ó¿Ú£©ÀàÐÍ¡£ÔÚÏÂÁîÐÐģʽÏ£¬PHP_SAPI ³£Á¿µÄֵͨ³£ÊÇ cli£¬¶øÔÚ Web Ó¦ÓóÌÐòÖУ¬ÔòÊÇ apache2handler »ò fpm-fcgi µÈ¡£
ÒÔÏÂÊÇʾÀý´úÂ룺
if (PHP_SAPI === 'cli') { // ÔÚÏÂÁîÐÐģʽÏÂÔËÐÐ echo 'Ä¿½ñÕýÔÚÔËÐÐÏÂÁîÐÐģʽ'; } else { // ÔÚ Web ģʽÏÂÔËÐÐ echo 'Ä¿½ñÕýÔÚÔËÐÐ Web ģʽ'; }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊö´úÂëÖУ¬ÎÒÃÇʹÓà PHP_SAPI ³£Á¿À´ÅÐ¶Ï Laravel ÕýÔÚÄÄÖÖģʽÏÂÖ´ÐС£ÈôÊÇ PHP_SAPI µÄֵΪ cli£¬ÔòÅúעĿ½ñÓ¦ÓóÌÐòÔÚÏÂÁîÐÐģʽÏÂÔËÐУ¬²»È»¾ÍÊÇÔÚ Web ģʽÏÂÔËÐС£
³ýÁË¿ÉÒÔÔÚ´úÂëÖÐʹÓà PHP_SAPI ³£Á¿Í⣬ÎÒÃÇ»¹¿ÉÒÔͨ¹ý Laravel ÌṩµÄ App ¹¤¾ßÀ´ÅжÏÄ¿½ñ³ÌÐòµÄÔËÐÐģʽ¡£ÀýÈ磬ÈôÊÇÎÒÃÇÏ£ÍûÔÚÓ¦ÓóÌÐòÖоÙÐвî±ðµÄÉèÖã¬ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏ´úÂ룺
if (App::runningInConsole()) { // ÔÚÏÂÁîÐÐģʽÏÂÔËÐÐ echo 'Ä¿½ñÕýÔÚÔËÐÐÏÂÁîÐÐģʽ'; } else { // ÔÚ Web ģʽÏÂÔËÐÐ echo 'Ä¿½ñÕýÔÚÔËÐÐ Web ģʽ'; }
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂëÖУ¬ÎÒÃÇʹÓÃÁË App ¹¤¾ßµÄ runningInConsole() ÒªÁ죬¸ÃÒªÁ콫·µ»ØÒ»¸ö²¼¶ûÖµ¡£ÈôÊÇÄ¿½ñ Laravel Ó¦ÓóÌÐòÕýÔËÐÐÔÚ CLI ģʽÏ£¬Ôò¸ÃÒªÁ콫·µ»Ø true£¬²»È»½«·µ»Ø false¡£
³ýÁËʹÓà runningInConsole() ÒªÁ죬App ¹¤¾ß»¹ÌṩÁËÐí¶à²î±ðµÄÒªÁ죬¿ÉÒÔÈÃÎÒÃÇÇáËɵĻñÈ¡Ä¿½ñ³ÌÐòµÄÆäËûÊôÐÔºÍÇéÐαäÁ¿¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔʹÓà environment() ÒªÁìÀ´»ñÈ¡Ä¿½ñÓ¦ÓóÌÐòµÄÇéÐαäÁ¿£¬ÒÔ¾öÒéÔÚÄĸöÇéÐÎÖÐÔËÐÐÓ¦ÓóÌÐò¡£
×ܵÄÀ´Ëµ£¬Í¨¹ýÅÐ¶Ï Laravel ÊÇ·ñÔËÐÐÔÚ CLI ģʽÏ£¬¿ÉÒÔ×ÊÖúÎÒÃǸüºÃµØʹÓÿò¼ÜÌṩµÄ¹¦Ð§ºÍ×ÊÔ´¡£ÎÞÂÛÊÇÔÚ Web ģʽÏÂÕÕ¾ÉÔÚ CLI ģʽÏ£¬Laravel ÌṩÁËÖÚ¶àÓÐÓõŤ¾ßºÍÊÖÒÕ£¬¿ÉÒÔ×ÊÖúÎÒÃǸü¿ìËÙ¡¢¸ßЧµØ¿ª·¢Ó¦ÓóÌÐò¡£
ÒÔÉϾÍÊÇlaravel ÅжÏÊÇ·ñcliµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡