DEV Community

Igor Ilic
Igor Ilic

Posted on

PHP routing library for fast API development

GitHub logo gigili / PHP-routing

Custom PHP routing library especially useful for fast API development

What it is?

PHP Routing is a custom written routing library that was inspired by the Slim framework. It was written as a small and lightweight alternative to it as I needed to use something with as little overhead as possible (not that Slim has a big foot print, hence the name Slim :D ). The first version of the library was consisting of a single PHP class that was able to handle static and some basic dynamic routes and had a semi working support for adding and using middlewares.

At first that was more than enough for my use case and the library was left at that, but recently I started rewriting one of my personal projects Did You Buy It? live on my Twitch channel and decided I wanted to use PHP for it, as the original API was developed using Node and Express.

What does it do?

This library allows for quick API development with support for both static and dynamic routes. It has support for adding prefixes to routes (ability to group them), add middlewares to be executed before the routes are processed. I'm also working on some new features but if you feel like something is missing or would like to see it implemented do leave feedback on the project.

A small sample on how to add your own routes:

$routes = new Routes;

$routes->add('/', function() { echo "Hello world"; }, Routes::GET); // If the request method is not specified the GET method is used by default

    function(Request $request, int $userID, bool $isPublished){
        //Do something
    [Routes::GET, Routes::POST]

Enter fullscreen mode Exit fullscreen mode

Why did I build it?

At my day job we needed to develop an API and I've never really tried to build one using vanilla PHP, but instead used frameworks such as CodeIgniter or Slim or just a simple file that would mimic the functionality of an API but not be a proper one. Also we had a requirement that we needed to have full control over the code so we were not supposed to use any of the pre built solutions because of that requirement.

I thought I would look into how to build my own routing library and implement it for our use case. I started of by taking a look at the source code of Slim framework but also just by looking around the web for examples of what other people had done before. One of the video tutorials that really inspired me and I used it as guide while developing this was the one from Codecourse on youtube on how to build your own MVC app.

Where to find it ?

You can find the source code of the library on my GitHub, but also on the Packagist website and use it as a composer package.

GitHub logo gigili / PHP-routing

Custom PHP routing library especially useful for fast API development

Stay in touch

If you want to reach out to me, you can do so on my Twitter, GitHub or Twitch

Top comments (0)