Using Middleware in CakePHP “3.next”
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
6 comments