Cygnite - A Modern Toolkit For Web Developers

The Elegant Way of Building Full-Featured Web Applications

Cygnite Dynamic Routing

Middleware


Documentation


HTTP Middleware

Introduction

HTTP middleware are classes which executes between Kernel and the Controller. Middleware are use to manipulate the Http request send request back to the Pipeline. Middleware are executed in series in a Pipeline. It allows you to perform some actions before passing the request to the Controller. For example: Http middleware can be used to verify and authenticate the user to your application. If user not authenticated middleware will redirect the user to login page.

Creating A Middleware

You may create a middleware class in the src/Apps/Middleware directory. Let us take a look at example middleware class:


namespace Apps\Middleware;

use Closure;
use Cygnite\Http\Requests\Request;
use Cygnite\Http\Responses\Response;
use Cygnite\Http\Responses\ResponseHeader;
use Cygnite\Http\Responses\RedirectResponse;

/**
 * Class AccessMiddleware
 *
 * Application middleware will be executed before passing the
 * request to application's controller.
 *
 * @package Apps\Middleware
 */
class AccessMiddleware
{
    /**
     * Restrict user to access the application if user
     * not belong to particular IP address.
     *
     * @param Request $request
     * @param callable $next
     * @return static
     */
    public function handle(Request $request, Closure $next)
    {
        if ($request->server->get('REMOTE_ADDR') !== '192.168.23.1') {
            return Response::make('Forbidden', ResponseHeader::HTTP_UNAUTHORIZED);
        }

        return $next($request);
    }
}
 

In the above example we will only allow access to the application if the remote IP is not 192.168.23.1, meaning that handle methods get called before processing HTTP request to your application. Otherwise, we will return "Forbidden" error response back to the browser.

Note: If middleware does not call the $next closure, none of the middleware after it in the pipeline will be run.

Shutdown Middleware

You may wish to perform some action after processing the HTTP request to your application. You can do so simply adding a shutdown method into your HTTP middleware class. It will get executed after HTTP request processed.

 
 
    /**
     * Executes after HTTP processed
     *
     * @param Request $request
     * @param Response $response
     */
    public function shutdown(Request $request, Response $response)
    {
     
    }

Registering Middleware

You must register a middleware to be executed on every HTTP request to your application, simply add an entry of middleware class in the $middleware property of your src/Apps/Kernel.php class. Let us take a look at an example:



namespace Apps;

use Cygnite\Foundation\Application;
use Cygnite\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        '\Apps\Middleware\AccessMiddleware'
    ];

    public function __construct(Application $app)
    {
        parent::__construct($app);
    }
}
 

Note: If you wish to perform some task before application boot up then you can use constructor of \Apps\Kernel class

Dependency Injection in Middleware

Middleware also allows dependency injection for the type-hinted class in a constructor. So if you require some objects in your handle() method, you just specify in the constructor. Let us take a look at an example:


namespace Apps\Middleware;

use Closure;
use Apps\Middleware\Auth\Authenticator;
use Cygnite\Http\Responses\RedirectResponse;

class AuthMiddleware
{
    private $authenticator;

    public function __construct(Authenticator $authenticator)
    {
       $this->authenticator = $authenticator;

    }

    public function handle($request, Closure $next)
    {
        if (!$this->authenticator->isLoggedIn()) {
            return new RedirectResponse("/login");
        }
        
        return $next($request);
    }

} 

Manipulating The Request

You can manipulate the HTTP request before it passes to the controller. You just need to make changes and manipulate the request object before calling to $next($request). For example:


namespace Apps\Middleware;

use Closure;
use Cygnite\Http\Requests\Request;

class RequestManipulatorMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        // Add some header before returning $next($request)
        $request->header->add("SOME_HEADER_FOO", "foobar");

        return $next($request);
    }
}


Manipulating The Response

Similarly you can also manipulate the Http Response after the controller/routes has done its work. Let us take a look at an example:


namespace Apps\Middleware;

use Closure;
use Cygnite\Http\Requests\Request;
use Cygnite\Common\Input\CookieManager\Cookie;

class ResponseManipulatorMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        
        Cookie::create(function ($cookie)
        {
            $cookie->name('cygnite_cookie')
                ->value('Cygnite Framework Cookie')
                ->expire((time()+3600))
                ->path('/')
                ->store();

            return $cookie;
        });

        return $response;
    }
}


Assigning Middlewares To Routes

You can assign the middlewares to your routes, simply by adding a middleware key in the HTTP route method, and the Middleware class name as value. Let us take a look at example:


$app->router->get('/user/profile/{:name}', ["middleware" => "Apps\Middleware\RouteMiddleware",
    function ($router, $name) {
        return "Hello $name";
    }
]);


The Apps\Middleware\RouteMiddleware::handle() method will get executed before processing route request. Read more about routes middlewares.

Follow Us On Facebook Twitter Google+ Linkedin
Released Under The MIT Public License. Copyrights @2012-2017. Powered by- Sanjoy Dey Productions.