laravelÔõôÉèÖÃÇëÇóÍ·
laravel ÊÇÒ»¸öÊ¢ÐÐµÄ php ¿ò¼Ü£¬ËüÌṩÁ˸»ºñµÄ¹¦Ð§ºÍÓÅÒìµÄÉè¼Æģʽ£¬À´×ÊÖúÎÒÃǹ¹½¨¸ßЧ¡¢¿Éά»¤µÄ web Ó¦ÓóÌÐò¡£ÔÚÏÖʵ¿ª·¢ÖУ¬ÓÐʱ¼äÎÒÃÇÐèÒªÔÚ laravel Ó¦ÓóÌÐòµÄÇëÇóÍ·ÖÐÉèÖÃһЩ×Ô½ç˵µÄÐÅÏ¢£¬±¾ÎĽ«ÏÈÈÝÔõÑùÔÚ laravel ÖÐÉèÖÃÇëÇóÍ·¡£
ʹÓà middleware ÉèÖÃÇëÇóÍ·
ÔÚ Laravel ÖУ¬ÎÒÃÇ¿ÉÒÔʹÓà middleware ÖÐÑë¼þÀ´ÉèÖÃÇëÇóÍ·¡£ÔÚ Laravel Ó¦ÓóÌÐòÖУ¬middleware ÊÇÓÃÀ´´¦Àí HTTP ÇëÇóºÍÏìÓ¦µÄÀú³ÌÖеÄÒ»¸öÌØÊâ×é¼þ¡£Òò´Ë£¬Ê¹Óà middleware ÉèÖÃÇëÇóÍ·ÊÇÒ»¸öÓÅÒìµÄÑ¡Ôñ¡£
ÎÒÃÇ¿ÉÒÔʹÓà Laravel µÄ make:middleware ÏÂÁîÀ´½¨ÉèÒ»¸ö middleware£º
php artisan make:middleware SetCustomHeader
µÇ¼ºó¸´ÖÆ
ÔÚн¨ÉèµÄ SetCustomHeader ÀàÖУ¬ÎÒÃÇ¿ÉÒÔÔÚ handle ÒªÁìÖÐÌí¼ÓÎÒÃÇÐèÒªµÄÇëÇóÍ·ÐÅÏ¢£º
namespace App\Http\Middleware; use Closure; class SetCustomHeader { public function handle($request, Closure $next) { $request->headers->set('Custom-Header', 'Custom Value'); return $next($request); } }
µÇ¼ºó¸´ÖÆ µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇʹÓà $request->headers->set() ÒªÁìÀ´ÉèÖÃÇëÇóÍ·ÐÅÏ¢¡£ÕâÀïµÄ Custom-Header ÊÇ×Ô½ç˵µÄÍ·ÐÅÏ¢Ãû³Æ£¬Custom Value ÊÇÎÒÃÇËùÉèÖõÄ×Ô½ç˵ֵ¡£
ÔÚÉèÖÃÍê middleware ºó£¬ÎÒÃÇ»¹ÐèÒª½«Æä×¢²áµ½Ó¦ÓóÌÐòµÄÈ«¾Ö middleware ÖС£ÔÚ app/Http/Kernel.php ÎļþÖУ¬ÖÐÑë¼þÊý×é $middlewareGroups ÖÐÌí¼ÓÎÒÃǵÄРmiddleware£º
protected $middlewareGroups = [ 'web' => [ // other middleware \App\Http\Middleware\SetCustomHeader::class, ], // other middleware groups ];
µÇ¼ºó¸´ÖÆ
È»ºó£¬ÎÒÃǾͿÉÒÔ×îÏÈʹÓÃеÄ×Ô½ç˵ÇëÇóÍ·ÁË¡£
ʹÓÃÈ«¾Ö middleware ÉèÖÃÇëÇóÍ·
ÔÚ Laravel ÖУ¬ÎÒÃÇÒ²¿ÉÒÔʹÓÃÈ«¾Ö middleware À´ÉèÖÃÇëÇóÍ·¡£È«¾Ö middleware »áÔÚÿ¸öÇëÇó´¦ÀíÀú³ÌÖж¼±»Ö´ÐУ¬Òò´Ë£¬È«¾Ö middleware Ò²¿ÉÒÔºÜÀû±ãµØÉèÖÃÇëÇóÍ·ÐÅÏ¢¡£
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÔÚÓ¦ÓóÌÐòµÄÈ«¾Ö middleware ÖÐ×¢²áÒ»¸öÐ嵀 middleware£º
protected $middleware = [ // other middleware \App\Http\Middleware\SetCustomHeader::class, ];
µÇ¼ºó¸´ÖÆ
È»ºó£¬ÎÒÃÇ¿ÉÒÔÏñÉÏÒ»½ÚÖÐÄÇÑù£¬ÔÚ middleware ÀàÖÐÉèÖÃ×Ô½ç˵ÇëÇóÍ·ÐÅÏ¢£º
namespace App\Http\Middleware; use Closure; class SetCustomHeader { public function handle($request, Closure $next) { $request->headers->set('Custom-Header', 'Custom Value'); return $next($request); } }
µÇ¼ºó¸´ÖÆ µÇ¼ºó¸´ÖÆ
×îºó£¬ÎÒÃÇ¿ÉÒÔÏñƽʱһÑùʹÓà Laravel µÄÇëÇóºÍÏìÓ¦¹¦Ð§£¬ËüÃÇ»á°üÀ¨ÎÒÃǸոÕÉèÖõÄ×Ô½ç˵ÇëÇóÍ·¡£
×ܽá
ÔÚ±¾ÎÄÖУ¬ÎÒÃÇÏÈÈÝÁËÔõÑùÔÚ Laravel ÖÐÉèÖÃ×Ô½ç˵µÄÇëÇóÍ·ÐÅÏ¢¡£ÎÒÃÇ¿ÉÒÔʹÓà middleware »òÈ«¾Ö middleware À´ÊµÏÖÕâ¸ö¹¦Ð§¡£ÎÞÂÛÊÇÄÄÖÖ·½·¨£¬ÉèÖÃÇëÇóÍ·ÐÅÏ¢¶¼ÊǺÜÊǼòÆӵġ£Í¨¹ýÉèÖÃ×Ô½ç˵µÄÇëÇóÍ·ÐÅÏ¢£¬ÎÒÃÇ¿ÉÒÔΪӦÓóÌÐòÌí¼Ó¸ü¶àµÄ¹¦Ð§ºÍÌØÕ÷¡£
ÒÔÉϾÍÊÇlaravelÔõôÉèÖÃÇëÇóÍ·µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡