Building a PHP Framework: Part 8 – Routing

Part 7 got us up to speed on the container that will be used in the Analyze PHP Framework. In this post we’ll cover how routing works in general and specifically within PHP.

How Routing Works

Routing is the process of parsing a URI and determining the appropriate action to take.

For example, consider the following URI:

How does a request like the one above result in a response to the user? Let’s break it down:

  1. The request is received by the application.1
  2. The application breaks down the request into its components. Things like: the method (ex: GET), host, path, etc.
  3. The application looks for a defined route that matches this request.
  4. Once found, it takes the defined action and returns a response.

A Laravel Example

For a real-world example, here’s one way the above example could be implemented in Laravel.

We define a GET route for the /login URI. When that route is requested we return a response – in this case, HTML for the login page.

How Routers Work

There are a number of routers in the PHP ecosystem. They range from the more simplistic to feature-packed behemoths. Although they differ in size and complexity, they generally employ the same fundamental steps: parse the request, match the pattern, run some code, return a response.

The Symfony router (probably the most widely used PHP router) does this.

As does this one.

And this one.

A Very Simple PHP Router

To demonstrate these concepts let’s create a stupid simple, not at all useful, PHP router.

Run The Code

  1. Save this code locally as index.php.
  2. In your terminal navigate to the directory where you saved the script.
  3. Start the built-in PHP web server: php -S localhost:1234
  4. In your browser go to: http://localhost:1234/hello

Conclusion

I’ve touched on the very basics of routing, shared some routing examples from the PHP world, and built a extremely simple router. On a related note, I’ve started work on the router that will be used in the Analyze PHP framework. To keep up to speed on it, be sure to follow @AnalyzePHP on Twitter.

One last thing, be sure to checkout my newsletter! Each week I’ll send you a great email filled with updates, great links, tips & tricks, and other non-dev randomness. If you’re interested you can sign up using the form in the sidebar to the right 👉 or follow this link.

Footnotes

  1. There are a number of steps before the application receives a request. They’ve been left out for brevity. See: How Does The Internet Work?