-
Inregistrare Middleware
-
Parametri MiddMiddleware
-
Middleware Terminabil
Middleware actioneaza ca un intermediar intre cerere si raspuns, asigura un mecanism pentru filtrare cereri HTTP.
Spre exemplu Laravel include un middleware care verifica daca utilizatorul aplicatiei este autentificat sau nu. Daca utilisatorul este autentificat, el va fi redirectionat catre homepage, altfel va fi redirectionat catre pagina de login.
Exista cateva middleware incluse in framework-ul Laravel, inclusiv middleware pentru autentificare si protectie CSRF. Toate aceste middleware-uri sunt localizate in directorul
app/Http/Middleware/.
Definire Middleware
Poti crea propriul middleware pentru a filtra si a prelucra cererile inainte de a returna raspunsuri.
Pentru a crea un Middleware poti folosi comanda '
artisan make:middleware' in CLI.
php artisan make:middleware MiddlewareName
- Exemplu, in interfata Command Line, navigheaza catre directorul cu proiectul Laravel si executa aceasta comanda pentru a crea un middleware CheckAge:
php artisan make:middleware CheckAge
Aceasta va crea un nou fisier numit "
CheckAge.php" in directorul
app/Http/Middleware/ cu o clasa CheckAge si o metoda handle():
namespace App\Http\Middleware;
use Closure;
class CheckAge {
//Handle an incoming request.
//@param \Illuminate\Http\Request $request
//@param \Closure $next
//@return mixed
public function handle($request, Closure $next){
if($request->age <=200) echo $request->age; //added for tests
return $next($request);
}
}
- Am adaugat linia de cod "
if($request->age <=200)" pentru a o folosi pentru testare.
Metoda middleware handle() este executata inaintea controller-ului.
Inregistrare Middleware
Inainte de a folosi un middleware, trebuie sa il inregistrezi in clasa
app/Http/Kernel.php. Aceasta clasa contine trei proprietati:
$middleware, $routeMiddleware, $middlewareGroups.
Exista doua tipuri de Middleware in Laravel: Global Middleware si Route Middleware.
Global Middleware
Global Middleware va rula automat la fiecare cerere HTTP a aplicatiei.
Pentru a inregistra un Global Middleware, adauga clasa la sfarsitul proprietatii
$middleware, cum e in codul de mai jos.
- Aici aveti un exemplu pentru testare.
1. Adauga clasa CheckAge in proprietatea $middleware' (in clasa
app/Http/Kernel.php).
protected $middleware =[
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckAge::class //-for test
];
2. Acum, acceseaza aceste adrese URL in browser:
Aceasta adresa va afisa 99; datorita: "if($request->age <=200) echo $request->age;" in CheckAge middleware
//localhost:8000/?age=99
Acest URL nu afisaza 299; deoarece age e mai mare de 200
//localhost:8000/?age=299
Route Middleware
Route Middleware va fi alocat unui route specific.
Pentru a inregistra un Route Middleware, adauga-l in lista proprietatii
$routeMiddleware, si atribuie-i un index care doresti, ca in codul de mai jos.
De exemplu:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'age'=> \App\Http\Middleware\CheckAge::class //-for test
];
Dupa ce middleware-ul a fost adaugat in proprietatea $routeMiddleware, poti folosi metoda middleware pentru a atribui middleware-ul unui route (cu indexul care a fost inregistrat):
Route::get('admin/profile', function(){
//
})->middleware('auth');
- De asemenea, poti folosi mai multe middleware-uri la un Route:
Route::get('/', function(){
//
})->middleware('auth', 'age');
Poti de asemenea folosi o clasa middleware fara a o inregistra in Kernel.php, incluzand-o cu "
use" in "
routes/web.php".
Apoi, trece
ClassName::class in metoda
middleware() in Route:
use App\Http\Middleware\CheckAge;
Route::get('admin/profile', function(){
//
})->middleware(CheckAge::class);
Grupe de Middleware
Grupe de Middleware (
Middleware Groups) se foloseste pentru a grupa mai multe middleware-uri in acelasi nume (index).
Pentru a crea un grup de middleware, se foloseste proprietatea
$middlewareGroups in Kernel.php.
- Laravel vine cu grupurile de middleware "
web" si "
api" care contin middleware-uri comune pe care ai vrea poti sa le aplici la web UI si Rutele API:
protected $middlewareGroups = [
'web' =>[
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class
],
'api' =>[
'throttle:60,1',
'bindings'
],
//for exemplification
'group_name'=>[
\App\Http\Middleware\Middleware::class,
\App\Http\Middleware\OtherMiddleware::class,
]
];
Grupul middleware 'web' este aplicat automat la fisierul routes/web.php de catre RouteServiceProvider.
Grupele middleware pot fi folosite la Route si actiuni catre controller folosind aceasi sintaxa ca si la middleware-uri individuale:
//assign middleware group_name to this route
Route::get('/', 'MyController@index')->middleware('group_name');
//assign group_name to a group of routes
Route::group(['middleware' => ['group_name']], function () {
//here you can add several routes
});
Parametri Middleware
Middleware poate de asemenea primi parametri aditionali. Poti adauga parametri dupa argumentul
$next in metoda middleware.
- De exemplu putem seta un parametru
$role in metoda
handle() a clasei middleware pe care am creat-o.
public function handle($request, Closure $next, $role){
echo $role;
return $next($request);
}
Parametri Middleware poti fi specificati cand se defineste route-ul prin separarea numelui de inregistrare middleware si parametrilor cu ":"
//pass 'role_value' for the first additional parameter ($role) to middleware registered with the key 'age' in $routeMiddleware (in Kernel.php)
Route::name('home')->get('/', 'MyController@index')->middleware('age:role_value');
- Acum daca accesezi "
//localhost:8000/", va arata sirul "role_value".
Middleware Terminabil
Middleware terminabil (
Terminable middleware) executa anumite instructiuni
dupa ce raspunsul a fost trimis catre browse.
- Metoda
handle() a clasei middleware este executata
inainte de a trimite Request-ul la controller.
Pentru a efectua anumite instructiuni dupa ce raspunul a fost trimis browser-ului, defineste o metoda
terminate() in clasa middleware.
Metoda terminate() trebuie sa primeasca argumentele $request si $response.
namespace App\Http\Middleware;
use Closure;
class CheckAge {
//Handle an incoming request.
//@param \Illuminate\Http\Request $request
//@param \Closure $next
//@return mixed
public function handle($request, Closure $next){
if($request->age <=200) echo $request->age;
return $next($request);
}
//executed after the response has been sent to browser
public function terminate($request, $response){
echo '<br>Executing statements of terminate method of CheckAge.';
}
}
- Middleware-ul terminabil trebuie inregistrat in lista proprietatilor
$middleware sau
$routeMiddleware in
app/Http/Kernel.php.
Metoda
terminate() va fi apelata automat dupe ce raspunsul este trimis catre browser.
- Documentatie:
Laravel - Middleware