Welcome to Abdul Malik Ikhsan's Blog

Using Middleware in CakePHP “3.next”

Posted in CakePHP by samsonasik on May 29, 2016

Middleware support will be come in CakePHP 3.3.0, but you can try it now, there is a branch for it named “3.next”! If you want to start with composer create-project, you can run with the following command:

composer create-project --prefer-dist cakephp/app <dir-target> dev-3.next

By specifying “dev-3.next” after directory target, you will pull the 3.next branch of “cakephp/app”. Once it done, you will now have an Application class inside src/ that bootstrap the application and also setup the middleware your application will use:

namespace App;

class Application extends BaseApplication
{
    public function bootstrap(){ /** **/}

    public function middleware($middleware)
    {
        $middleware->push(new ErrorHandlerMiddleware());
        $middleware->push(new AssetMiddleware());
        $middleware->push(new RoutingMiddleware());

        return $middleware;
    }
}

Now, let say you want to add your own middleware, named “Authorization” middleware, let’s create it:

namespace App\Middleware;

use Cake\Network\Session;
use Cake\Core\Configure;
use Zend\Diactoros\Response\RedirectResponse;

class Authorization
{
    public function __invoke($request, $response, $next)
    {
        $session             =  Session::create(Configure::read('Session'));
        $checkHasUserSession = $session->check('user');

        $path = $request->getUri()->getPath();
        if ($path === '/admin' && ! $checkHasUserSession) {
            return new RedirectResponse('/auth');
        }

        return $next($request, $response);
    }
}

The “Authorization” middleware we just created now needs to be registered via middleware->push:

namespace App;

use App\Middleware\Authorization;

class Application extends BaseApplication
{
    public function middleware($middleware)
    {
        $middleware->push(new ErrorHandlerMiddleware());
        $middleware->push(new AssetMiddleware());
        $middleware->push(new RoutingMiddleware());
        
        //add the Authorization middleware
        $middleware->push(new Authorization());

        return $middleware;
    }
}

Done 😉

References:
1. http://www.slideshare.net/markstory/future-of-http-in-cakephp

Advertisements
Tagged with: ,

4 Responses

Subscribe to comments with RSS.

  1. Rayn said, on September 7, 2016 at 1:53 am

    I am getting ‘The page isn’t redirecting properly’ error while redirecting using below code .

    public function __invoke($request, $response, $next)
    {
    $path = $request->getUri()->getPath();
    if ($path === ‘/admin/index’) {
    return new RedirectResponse($path,200);
    }
    return $next($request, $response);
    }

    I am new to cakephp and I would like to create a middleware to authenticate each controller action. Above code is an example.

    • samsonasik said, on September 7, 2016 at 3:30 pm

      because your code is redirect to same page with current page, check your code:

      if ($path === ‘/admin/index’) {
      return new RedirectResponse($path,200);
      }
      

      that will always got endless redirect.

  2. Harry Reihet said, on October 3, 2016 at 2:13 am

    how can i create unit test for session on middleware?
    i’ve tried using common session property, or using Session::write, neither of it can read the session when tested

    thx in advance


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: