PHP code example of tdw / routing

1. Go to this page and download the library: Download tdw/routing library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tdw / routing example snippets




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



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



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'));



$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);



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

var_dump($currentRoute);



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());