DEV Community

Cover image for Middleware and model binding in Mezon Router
alexdodonov
alexdodonov

Posted on • Edited on

1 2

Middleware and model binding in Mezon Router

Hi all! According to this issue I have implemented feature request. As you can see it was abou model binding.

Let's see how it works.

You can register your own middleware wich will be called before the route handler will be executed. This middleware can transform common parameters $route and $parameters into something different.

Here is the example:

$router = new Router();
$router->addRoute('/user/[i:id]', function(string $route, array $parameters){
    $userModel = new UserModel();
    $userObject = $userModel->getUserById($parameters[$id]);

    // use $userObject for any purpose you need
});
Enter fullscreen mode Exit fullscreen mode

Quite simple, but you can register middleware wich will do all dirty job:

$router = new Router();
$router->addRoute('/user/[i:id]', function(UserObject $userObject){
    // here we get $userObject directly
    // use use it in any way we need
});
$router->registerMiddleware('/user/[i:id]', function(string $route, array $parameters){
    $userModel = new UserModel();
    $userObject = $userModel->getUserById($parameters[$id]);
    return $userObject;
});
Enter fullscreen mode Exit fullscreen mode

And here we get model binding.

Learn more

More information can be found here:

Twitter
Mezon Framework

It will be great if you will contribute something to this project. Documentation, sharing the project in your social media, bug fixing, refactoring, or even submitting issue with question or feature request. Thanks anyway )

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay