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 )

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay