DEV Community

loading...
Cover image for Custom types in Mezon Router

Custom types in Mezon Router

alexdodonov
PHP developer
Updated on ・2 min read

Hi!

Since one of the last update of Mezon Router you can define your own types for URL parser. Let's try to create date type.

First of all we should create simple class:

class DateRouterType
{

    /**
     * Method returns regexp for searching this entity in the URL
     *
     * @return string regexp for searching
     */
    public static function searchRegExp(): string
    {
        return '(\[date:'.BaseType::PARAMETER_NAME_REGEXP.'\])';
    }
}
Enter fullscreen mode Exit fullscreen mode

Here BaseType::PARAMETER_NAME_REGEXP is a global setting wich tells router that parameter names must consist of:

  • a-z and A-Z letters
  • 0-9
  • and symbols _ and -

Now we need to define one more class method wich will parse date if it will occur:

public static function parserRegExp(): string
{
    // pretty simple regexp
    return '([0-9]{4}-[0-9]{2}-[0-9]{2})';
}
Enter fullscreen mode Exit fullscreen mode

And somewhere in your setup files you need to switch this type on:

$router->addType('date', DateRouterType::class);
Enter fullscreen mode Exit fullscreen mode

Now you can handle routes like this:

/some-url-part/2020-02-02/ending-part/
/posts-for-2020-02-02/
Enter fullscreen mode Exit fullscreen mode

But be careful. For example you will define such routes:

$router->addRoute('/posts-for-[date:posts-date]/', function(UserObject $userObject){
    // some activities here
});

$router->addRoute('/[s:some-url/', function(UserObject $userObject){
    // some activities here
});
Enter fullscreen mode Exit fullscreen mode

Then the first handler /posts-for-[date:posts-date]/ will be called for the route /posts-for-2020-02-02/.

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 )

Discussion (0)