Create a custom middleware

I’m new to CakePHP and I’m enjoying it so far, however I still have some basic questions.

I would like to know if I can create/apply a custom middleware in the routes file or in a specific controller. I also would like to know I that the methods beforeFilter() and beforeRender() or even initialize() could be used as middleware, as I would add my own logic before anything happens.

I mean, I think that the best rpactice would have a middleware set in the routes.php file, like so:

$routes->applyMiddleware('csrf');

But then I would like to add my own middleware, like this:

$routes->applyMiddleware('verifyUser');

Where could I define this verifyUser middleware and how I can create it?

Thank you in advance.

The CSRF middleware example would seem to answer this. First you use registerMiddleware to associate a name with an object (any object you want to create), and then applyMiddleware to apply that name to a route.

1 Like

Thank you, but how would I do that? Do I have to create a file in the same location as the csrf middleware?

When I said “any object you want to create”, what I was getting at is that you are responsible for creating the object to pass in there. If you look at the linked example, it’s doing new WhateverMiddleware(...). So, you can put your class literally anywhere in your namespace that it makes sense to put it. If you’re not clear on how PHP namespaces work, then I’d highly recommend doing some reading on that subject, as they’re pretty fundamental to how most everything in Cake comes together.

1 Like