Custom types in Mezon Router

Dodonov Alexey
Nov 11, 2020

--

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.'\])';
}
}

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})';
}

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

$router->addType('date', DateRouterType::class);

Now you can handle routes like this:

/some-url-part/2020-02-02/ending-part/
/posts-for-2020-02-02/

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
});

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

dev.to

Slack

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 )

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response