Skip to content

6. Middlewares

İzni Burak Demirtaş edited this page Nov 24, 2020 · 7 revisions

You can also use Middleware with PHP-Router. There are two ways to use Middleware; those are before method and after method.

Before

Before method runs before route action does not trigger yet.

Request -> BEFORE MIDDLEWARE -> Action -> After Middleware -> Response

After

After method runs after route action triggered.

Request -> Before Middleware -> Action -> AFTER MIDDLEWARE -> Response

Usage

# index.php file

$router = new \Buki\Router\Router([
  'paths' => [
      'controllers' => 'Controllers',
      'middlewares' => 'Middlewares',
  ],
  'namespaces' => [
      'controllers' => 'Controllers',
      'middlewares' => 'Middlewares',
  ],
]);

$router->get('/', 'IndexController@main', ['before' => 'FooMiddleware']);
# OR 
$router->get('/', 'IndexController@main', ['before' => FooMiddleware::class]);
# Middlewares/FooMiddleware.php
namespace Middlewares;

use Buki\Router\Http\Middleware;

class FooMiddleware extends Middleware
{
  public function handle()
  {
    // your middleware codes

    return true;
  }
}

Your middleware class must have a method that called handle().

This method must return true value if your middleware is pass. If the method returns another value except true, this mean middleware is not valid. So, your request will be blocked for routes which using this middleware. Another example:

# Middlewares/FooMiddleware.php
namespace Middlewares;

use Buki\Router\Http\Middleware;
use Symfony\Component\HttpFoundation\Request;

class FooMiddleware extends Middleware
{
  public function handle(Request $request)
  {
    if (!$request->getSession()->get('auth')) {
      // you can redirect another url here 
      // or 
      // you can write error message, view, json response, etc...

      return false;
    }

    return true;
  }
}

You must definitely specify return. Besides, return value should be true to pass and valid the middleware. Otherwise, your request will be blocked by the middleware for current route which using the middleware as i mentioned above.

Define Middleware in Controllers

You can define before and after middlewares in your Controllers. For example;

use Buki\Router\Http\Controller;
use Symfony\Component\HttpFoundation\Request;

class HomeController extends Controller
{
    /**
     * @var array Before Middlewares
     */
    public $middlewareBefore = [
        \FooMiddleware::class,
        'BarMiddleware',
    ];

    /**
     * @var array After Middlewares
     */
    public $middlewareAfter = [
        \BazMiddleware::class,
    ];

    /**
     * @param Response $response
     */
    public function main(Response $response)
    {
        return $response->setContent('Hello World');
    }
}
Clone this wiki locally