Create own PHP Router – Named URL Segments

This Custom PHP Router series is inspired from Laravel's router. This is second instalment in the series of create your own PHP router.

Reading Time: < 1 minute

This article is the second in the series of creating own PHP router, if you’ve missed the first part, check out here: Create your own PHP router the simplest way possible.

Named URL segments are generally more of like Laravel named routes with parameters. For instance, a named URL segment would look like:

Also checkout, Tidy up Code with Laravel Route Model Binding

Route::get('companies/{companyName},function(){...});

To make this work, you simply need to modify $action param in your router method to accept these named url segments when called from the browser.

$action = preg_replace('/{[^]+}/','(.+)',$action);

Well thats it, try this approach out and let us know if this works for you. You can also redo your memory by checking out the “Creating your own PHP router the simplest way possible – Part 1“.

Youtube Video

If you’re more of a video guy, checkout the detailed steps & explanation of this episode by Azeem Hassni. If you’ve any questions of feedback, you can leave us a comment here or ping the creator directly on his twitter. Happy coding.

Comments