zippy1981/php-routing-example

Example of custom PHP routing

v0.3 2019-04-30 15:40 UTC

This package is auto-updated.

Last update: 2024-04-29 04:03:21 UTC


README

CI/CD

CircleCI codecov

Composer stats

Latest Stable Version Total Downloads Latest Unstable Version License

Download stats

Monthly Downloads Daily Downloads

Using

  1. Create a project with composer init and follow the prompts.
  2. composer require zippy1981/php-example-routes.
  3. Create a namespace to store your controllers.
  4. Add an index.php with the following:
<?php
use \Router\Router;

/**
 * This makes our life easier when dealing with paths. Everything is relative
 * to the application root now.
 */
chdir(dirname(__DIR__));

// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server') {
    $path = realpath(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
    if (__FILE__ !== $path && is_file($path)) {
        return false;
    }
    unset($path);
}

// Composer autoloading
include __DIR__ . '/../vendor/autoload.php';

$container = new DI\Container();


if (! class_exists(Router::class)) {
    throw new RuntimeException(
        "Unable to load Router.\n"
        . "- Type `composer install` if you are developing locally.\n"
        . "- Type `docker-compose exec web composer install` if you are using Docker.\n"
    );
}

Router::setControllerRoot('YourControllerNamespace');
Router::resource('whatever');           # parent level controller
Router::resource('whatever.whenever');  # chile level controller

$router = $container->get(Router::class);

$router->invokeControllerMethod();