CodeBlanks Logo Icon CodeBlanks

Routing structure

PHP course · Advanced · Lesson 56/92

Build a simple router with $_SERVER['REQUEST_METHOD'] and the URI.

Reading the request

Every request in a REST API carries two key pieces of data: the HTTP method (GET, POST, PUT, DELETE) and the request path (such as /tasks). In PHP you reach them through the $_SERVER superglobal: $_SERVER['REQUEST_METHOD'] gives the method and $_SERVER['PATH_INFO'] gives the path.

When testing in the CLI you set these values by hand, so you can verify the dispatch logic without a real server. Method and path together identify a route uniquely.

Storing routes

The addRoute method takes three parameters: $method, $path and $handler. On each call you push this triple into the $this->routes array. The handler may be a closure (anonymous function) or a function name; dispatch will call it.

Storing the triple as an associative array makes the match easy to search with a single foreach. Every route record shares the same shape.

Exercise Add the addRoute method

Add an addRoute method to the Router class. Its signature is public function addRoute(string $method, string $path, $handler): void. The method pushes the three values as an associative array into $this->routes with keys method, path and handler. The demo line adds one route and prints the count.

Show example solution
void. Inside, push with $this->routes[] = ["method" => $method, "path" => $path, "handler" => $handler];.
Example solution:
<?php
// REST API projesi: Router + addRoute

class Router {
    public array $routes = [];
    public function addRoute(string $method, string $path, $handler): void {
    $this->routes[] = ["method" => $method, "path" => $path, "handler" => $handler];
}
}

// Demo:
$router = new Router();
$router->addRoute("GET", "/tasks", "handleGet");
echo count($router->routes);

Test yourself

  1. Complete the method name

    public function ____(string $method, string $path, $handler): void { }
    Show answer
    public function addRoute(string $method, string $path, $handler): void { }
  2. What are the three parameters of addRoute, in order?

    • $handler, $method, $path
    • $path, $method, $handler
    • $method, $path, $handler
    • $method, $handler, $path
    Show answer

    $method, $path, $handler — Correct. Method first, then path, then handler; the route reads naturally this way.

  3. Match the addRoute parameters

    $method
    HTTP method
    $path
    Request path
    $handler
    Handler
    $routes
    Route list

All lessons in Advanced