tdw/routing

Simple router to GET, POST, PUT, PATCH, DELETE requests.

1.0.1 2018-12-25 18:37 UTC

This package is not auto-updated.

Last update: 2024-04-30 06:17:23 UTC


README

Simple router to GET, POST, PUT, PATCH, DELETE requests.

Build Status

Requirements

PHP: >=7.0

Install

$ composer require tdw/routing

require 'to/path/vendor/autoload.php';

Usage

Instance

<?php

$router = new \Tdw\Routing\Router();

Closure

<?php

$router->addGET(new \Tdw\Routing\Route('/', function (){
    echo 'Home page';
}, 'home'));

Action and route name

<?php

class ArticleAction
{
    /**
     * Route GET
     */
    public function index()
    {
        //
    }

    /**
     * Route POST
     */
    public function save()
    {
        //
    }
}

$router->addGET(new \Tdw\Routing\Route('/articles', 'ArticleAction@index', 'article.index'));
$router->addPOST(new \Tdw\Routing\Route('/articles/save', 'ArticleAction@save', 'article.save'));

Rule

<?php

$route = (new \Tdw\Routing\Route('/article/{slug}/{id}', function () {
    //
}, 'articles.show'))
    ->addRule('slug', new \Tdw\Routing\Rule\Slug())
    ->addRule('id', new \Tdw\Routing\Rule\Id());
$router->addGET($route);

Match

<?php

$currentRoute = $router->match(\GuzzleHttp\Psr7\ServerRequest::fromGlobals());

var_dump($currentRoute);

Exceptions

\Tdw\Routing\Exception\RouteNotFoundException
\Tdw\Routing\Exception\RouteNameNotFoundException

Suport for methods

- GET
- POST
- PUT
- PATCH
- DELETE

Integration suggestion

<?php

class App
{
    /**
     * @var \Tdw\Routing\Contract\Router
     */
    private $router;

    function __construct(\Tdw\Routing\Contract\Router $router)
    {
        $this->router = $router;
    }

    function run(\Psr\Http\Message\ServerRequestInterface $request)
    {
        if ($route = $this->router->match($request)) {
            if ($route->getCallback() instanceof Closure) {
                return call_user_func_array($route->getCallback(), $route->getParameters());
            }
            list( $action, $method ) = explode('@', $route->getCallback());
            return call_user_func_array([new $action, $method], $route->getParameters());

        }
        return new \GuzzleHttp\Psr7\Response(404, [], 'Page Not Found');
    }
}

(new App($router))->run(\GuzzleHttp\Psr7\ServerRequest::fromGlobals());

Contributing

Add new features.

License

The Tdw Routing is open-sourced software licensed under the MIT license.