PHP Concepts

PHP Concepts

Router

The router in PHP is responsible for directing HTTP requests to the appropriate logic in an application. It maps incoming requests (e.g., GET or POST) to specific controllers and methods. In frameworks like Laravel, routes are defined in dedicated files (e.g., web.php or api.php) and allow for route parameters, named routes, and middleware assignments. In a nutshell, a router is responsible for mapping requests to a function in your web application.

A route typically includes a URL pattern and the controller method it invokes.
Example:

PHP
Route::get('/users', [UserController::class, 'index']);

Dynamic route parameters allow passing data via URLs:

PHP
Route::get('/users/{id}', [UserController::class, 'show']);

Grouping routes under common prefixes or middleware simplifies organization.

For example this is the Router that I built for PHP:

PHP
<?php

namespace Core;
use Core\Middleware\Middleware;

class Router
{
    protected $routes = [];

    public function add($method, $uri, $controller)
    {
        $this->routes[] = [
            'uri' => $uri,
            'controller' => $controller,
            'method' => $method,
            'middleware' => null
        ];

        return $this;
    }

    public function get($uri, $controller)
    {
        return $this->add("GET", $uri, $controller);
    }

    public function post($uri, $controller)
    {
        return $this->add("POST", $uri, $controller);
    }

    public function delete($uri, $controller)
    {
        return $this->add("DELETE", $uri, $controller);
    }

    public function patch($uri, $controller)
    {
        return $this->add("PATCH", $uri, $controller);
    }

    public function put($uri, $controller)
    {
        return $this->add("PUT", $uri, $controller);
    }

    public function only($key)
    {
        $this->routes[array_key_last($this->routes)]["middleware"] = $key;

        return $this;
    }

    public function route($uri, $method)
    {
        foreach ($this->routes as $route) {
            if ($route['uri'] === $uri && $route['method'] === strtoupper($method)) {
                Middleware::resolve($route['middleware']);

                return require base_path("Http/controllers/" . $route['controller']);
            }
        }
        $this->abort();
    }

    public function previousUrl()
    {
        return $_SERVER["HTTP_REFERER"];
    }

    protected function abort($code = 404)
    {
        http_response_code($code);

        require base_path("views/{$code}.php");

        die();
    }
}

web.php:

PHP
<?php

$router->get("/", "index.php");
$router->get("/about", "about.php");
$router->get("/contact", "contact.php");

$router->get("/notes", "notes/index.php")->only("auth");
$router->get("/note", "notes/show.php");
$router->delete("/note", "notes/destroy.php");

$router->get("/notes/edit", "notes/edit.php");
$router->patch("/note", "notes/update.php");

$router->get("/notes/create", "notes/create.php");
$router->post("/notes", "notes/store.php");

$router->get("/books", "books/index.php")->only("auth");
$router->get("/book", "books/show.php");
$router->delete("/book", "books/destroy.php");

$router->get("/books/edit", "books/edit.php");
$router->patch("/book", "books/update.php");

$router->get("/books/create", "books/add.php");
$router->post("/books", "books/store.php");

$router->get('/register', 'registration/create.php')->only("guest");
$router->post('/register', 'registration/store.php')->only('guest');

$router->get('/login', 'session/create.php')->only('guest');
$router->post('/session', 'session/store.php')->only('guest');
$router->delete('/session', 'session/destroy.php')->only('auth');

Controller

The controller handles the logic associated with an HTTP request. It is a part of the MVC (Model-View-Controller) architecture and acts as a mediator between the router and the model/view. In PHP frameworks like Laravel, controllers often fetch data from models and pass it to views for rendering.
A controller is a PHP function you create that reads information from the Request object and creates and returns a Response object. The response could be an HTML page, JSON, XML, a file download, a redirect, a 404 error or anything else.

Controllers help keep the code organized and reusable by separating business logic from routing.

Resource controllers simplify ( CRUD = Create, Read, Update and Delete ) operations with pre-defined methods like index, create, store, edit, update, and destroy.
Example of creating a resource controller:

PHP
php artisan make:controller UserController --resource

For example it could look something like this:

Service Container

The service container in PHP (commonly used in frameworks like Laravel) is a dependency injection tool that manages class dependencies and their lifecycles. It resolves instances of classes automatically when they are required in other parts of the application. A Service Container (or dependency injection container) is simply a PHP object that manages the instantiation of services (i.e. objects)

The service container promotes loose coupling by avoiding hardcoding dependencies.

Dependencies can be registered in the container and resolved using the bind or singleton methods:

PHP
$this->app->bind('App\Interfaces\PaymentGatewayInterface', 'App\Services\StripePaymentGateway');

Laravel automatically resolves dependencies by type-hinting in constructors or methods:

PHP
public function __construct(PaymentGatewayInterface $paymentGateway) {
    $this->paymentGateway = $paymentGateway;
}

For example this is a simple Container:

PHP
<?php

namespace Core;

use Exception;

class Container
{
    protected $bindings = [];

    public function bind($key, $resolver)
    {
        $this->bindings[$key] = $resolver;
    }

    public function resolve($key)
    {
        if (!array_key_exists($key, $this->bindings)) {
            throw new \Exception("No matching binding found for {$key}");
        }
        $resolver = $this->bindings[$key];

        return call_user_func($resolver);
    }
}

Middleware

Middleware can be seen as some sort of bridge that connect an incoming request (HTTP-requests) or responses to the core of your application.

Middleware can be global (applied to all routes) or route-specific.
Middleware can modify requests before they reach the controller or modify responses before they return to the client.

Middleware is a powerful concept for enforcing policies or applying functionality across multiple routes. Learning to chain middleware and apply them appropriately helps to maintain clean and secure code.

Here’s an example of a Middleware code:
This example is to verify if the User is logged in or not and depending on which they can access the “register / login” page.

PHP
<?php

namespace Core\Middleware;

class Middleware
{
    public const MAP = [
        "guest" => Guest::class,
        "auth" => Auth::class
    ];

    public static function resolve($key)
    {
        if (!$key) {
            return;
        }

        $middleware = Middleware::MAP[$key] ?? false;

        if (!$middleware) {
            throw new \Exception("No matching middleware found for key '{$key}'.");
        }

        (new $middleware)->handle();
    }
}

Tags: