prob/router

A simple http request router library

dev-master 2016-10-23 08:13 UTC

This package is not auto-updated.

Last update: 2024-04-23 19:57:04 UTC


README

A simple http request router library

Build Status codecov

Usage

1. Configure url mapping and handler

url.mapping.php

<?php

use Prob\Router\Map;

$map = new Map();
$map->setNamespace('app\\controller');

$map->get('/', function ($url) {
    echo 'Hello main!';
});

$map->get('/test', 'Test.hello');
$map->get('/post/{post:int}', 'Post.view');

return $map;

2. Write your request handler (controller)

app/controller/Test.php

<?php

namespace app\controller;

class Test
{
    public function hello()
    {
        echo 'Test page!';
    }
}

app/controller/Post.php

<?php

namespace app\controller;

class Post
{
    public function hello($req)
    {
        echo 'Post ID: ' . $req['post'];
    }
}

3. Apply!

index.php

<?php

use Prob\Router\Dispatcher;
use Prob\Rewrite\Request;

// use zend-diactoros package (for PSR-7)
use Zend\Diactoros\Request;
use Zend\Diactoros\Uri;

$dispatcher = new Dispatcher(require 'url.mapping.php');
// print 'Hello main'
$dispatcher->dispatch(
    (new Request())
        ->withUri(new Uri('http://test.com/'))
        ->withMethod('GET')
);
// print 'Test page!'
$dispatcher->dispatch(
    (new Request())
        ->withUri(new Uri('http://test.com/test'))
        ->withMethod('GET')
);
// print 'Post ID: 5'
$dispatcher->dispatch(
    (new Request())
        ->withUri(new Uri('http://test.com/post/5'))
        ->withMethod('GET')
);