GithubHelp home page GithubHelp logo

router's Introduction

Hoa


Build status Code coverage Packagist License

Hoa is a modular, extensible and structured set of PHP libraries.
Moreover, Hoa aims at being a bridge between industrial and research worlds.

Hoa\Router

Help on IRC Help on Gitter Documentation Board

This library allows to find an appropriated route and extracts data from a request. Conversely, given a route and data, this library is able to build a request.

For now, we have two routers: HTTP (routes understand URI and subdomains) and CLI (routes understand a full command-line).

Learn more.

Installation

With Composer, to include this library into your dependencies, you need to require hoa/router:

$ composer require hoa/router '~3.0'

For more installation procedures, please read the Source page.

Testing

Before running the test suites, the development dependencies must be installed:

$ composer install

Then, to run all the test suites:

$ vendor/bin/hoa test:run

For more information, please read the contributor guide.

Quick usage

We propose a quick overview of two usages: in a HTTP context and in a CLI context.

HTTP

We consider the following routes:

  • /hello, only accessible with the GET and POST method;
  • /bye, only accessible with the GET method;
  • /hello_<nick> only accessible with the GET method.

There are different ways to declare routes but the more usual is as follows:

$router = new Hoa\Router\Http();
$router
    ->get('u', '/hello', function () {
        echo 'world!', "\n";
    })
    ->post('v', '/hello', function (Array $_request) {
        echo $_request['a'] + $_request['b'], "\n";
    })
    ->get('w', '/bye', function () {
        echo 'ohh :-(', "\n";
    })
    ->get('x', '/hello_(?<nick>\w+)', function ($nick) {
        echo 'Welcome ', ucfirst($nick), '!', "\n";
    });

We can use a basic dispatcher to call automatically the associated callable of the appropriated rule:

$dispatcher = new Hoa\Dispatcher\Basic();
$dispatcher->dispatch($router);

Now, we will use cURL to test our program that listens on 127.0.0.1:8888:

$ curl 127.0.0.1:8888/hello
world!
$ curl -X POST -d a=3\&b=39 127.0.0.1:8888/hello
42
$ curl 127.0.0.1:8888/bye
ohh :-(
$ curl -X POST 127.0.0.1:8888/bye
// error
$ curl 127.0.0.1:8888/hello_gordon
Welcome Gordon!
$ curl 127.0.0.1:8888/hello_alyx
Welcome Alyx!

This simple API hides a modular mechanism that can be foreseen by typing print_r($router->getTheRule()).

To unroute, i.e. make the opposite operation, we can do this:

var_dump($router->unroute('x', array('nick' => 'gordon')));
// string(13) "/hello_gordon"

CLI

We would like to recognize the following route [<group>:]?<subcommand> <options> in the Router.php file:

$router = new Hoa\Router\Cli();
$router->get(
    'g',
    '(?<group>\w+):(?<subcommand>\w+)(?<options>.*?)'
    function ($group, $subcommand, $options) {
        echo
            'Group     : ', $group, "\n",
            'Subcommand: ', $subcommand, "\n",
            'Options   : ', trim($options), "\n";
    }
);

We can use a basic dispatcher to call automatically the associated callable:

$dispatcher = new Hoa\Dispatcher\Basic();
$dispatcher->dispatch($router);

And now, testing time:

$ php Router.php foo:bar --some options
Group     : foo
Subcommand: bar
Options   : --some options

The use of the Hoa\Console library would be a good idea to interprete the options and getting some comfortable services for the terminal.

Documentation

The hack book of Hoa\Router contains detailed information about how to use this library and how it works.

To generate the documentation locally, execute the following commands:

$ composer require --dev hoa/devtools
$ vendor/bin/hoa devtools:documentation --open

More documentation can be found on the project's website: hoa-project.net.

Getting help

There are mainly two ways to get help:

Contribution

Do you want to contribute? Thanks! A detailed contributor guide explains everything you need to know.

License

Hoa is under the New BSD License (BSD-3-Clause). Please, see LICENSE for details.

router's People

Contributors

circlecode avatar hywan avatar jubianchi avatar k-phoen avatar lalop avatar metalaka avatar orthographic-pedant avatar osaris avatar shulard avatar stephpy avatar vonglasow avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

router's Issues

setSubdomainSuffix

When you define an subdomain suffix and you want make an unroute

$router->setSubdomainSuffix('foo');
$router
->get('p', '(?[^.]+)@/', 'project', 'list');

in xyl

the a.href output : http://hoathis.ark.imHiiiiii@/ instead of Hiiiiii.foo.hoathis.ark.im

Bye Hawk :) 👯

Automatically set the prefix for `Hoa\Router\Http`

Hello,

It would be great to have a magic way to autoset the prefix. Indeed, it's annoying if the user always needs to call the Hoa\Router\Http::setPrefix each time he is moving an application or changing server configuration.

On Apache, we can use the $_SERVER['SCRIPT_NAME'] value but it does not work with the PHP internal Web server. Does it work with other Web servers?

Any other ideas?

Routing not completed

Environnement :
windows 7
PHP 5.4.34

Problem :
My route is not dispatche correctly, so i speak with hywan and we try to isolate the problem with hoa/router.

So the code is :

$router = new Hoa\Router\Http();
$router->get('/supervisor', 'supervisor', 'index');
$router->route('/supervisor');

print_r(
$router->getTheRule()
);

The expected response :

Array
(
[0] => 0
[1] => /supervisor
[2] => Array
(
[0] => get
)

[3] => supervisor
[4] => index
[5] => 
[6] => Array
    (
        [_uri] => supervisor
        [_method] => get
        [_domain] => 
        [_subdomain] => 
        [_call] => index
        [_able] => 
        [_request] => Array
            (
            )

    )

)

And my response is :

Array
(
[0] => 0
[1] => supervisor
[2] => Array
(
[0] => get
)

[3] => /supervisor
[4] => supervisor
[5] => index
[6] => Array
    (
        [_uri] => supervisor
        [_method] => get
        [_domain] => bddobs.dev
        [_subdomain] => 
        [_call] => supervisor
        [_able] => index
        [_request] => Array
            (
            )

    )

)

Problème avec la variable prefix

Bonjour,

J'obtiens cette erreur :

( ! ) Hoa\Core\Exception\Error: preg_match(): Compilation failed: unmatched parentheses at offset 5 in \Hoa\Hoa\Router\Http.php on line 293

La ligne 293 étant celle-ci :

if(0 === preg_match('#^' . $prefix . '(.*)?$#', $uri, $matches))

Après avoir un peu regardé, cela viendrait de $prefix.
En fait pour moi $prefix vaut .
Je ne sais pas d'ou vient ce prefix chez moi.
Du coup la regexp donne quelque chose comme ceci :

if(0 === preg_match('#^\(.*)?$#', $uri, $matches))

Et donc cette regexp n'est en effet pas correct.

Les routes sont tout à fait "normales", car même celle-ci n'est plus acceptée :

$router->get('i', '/', 'blog', 'index')

Cannot found an appropriated rule to route favicon.ico.

<?php
require __DIR__ . '/vendor/autoload.php';

$router = new Hoa\Router\Http();
$router
    ->get('u', '/hello', function ( ) {

        echo 'world!', "\n";
    })
    ->get('v', '/bye', function ( ) {

        echo 'ohh :-(', "\n";
    })
    ->post('w', '/hello', function ( Array $_request ) {

        echo $_request['a'] + $_request['b'], "\n";
    })
    ->get('x', '/hello_(?<nick>\w+)', function ( $nick ) {

        echo 'Welcome ', ucfirst($nick), '!', "\n";
    });

$dispatcher = new Hoa\Dispatcher\Basic();
$dispatcher->dispatch($router);

Ran the server

php -S localhost:8000 index.php , requested route http://localhost:8000/hello

and getting

[Mon Apr  6 22:42:37 2015] PHP Fatal error:  Uncaught Hoa\Router\Http\Http::route(): (5) Cannot found an appropriated rule to route favicon.ico.
in /var/www/github.com/harikt/hoaproject/router/vendor/hoa/router/Http/Http.php at line 361.
  thrown in /var/www/github.com/harikt/hoaproject/router/vendor/hoa/router/Http/Http.php on line 361

No favicon is there though.

New subdomain feature

Hi :D

When you define $router->get('p', '(?[^.]+)@/', 'project', 'list');

And use unroute with an project empty variable , we have .hoathis.hoa i prefer have juste hoathis.hoa no ?

Its not a issue just a request feature :D

New feature : value control in unroute

Is it possible to have a value control in Router\Http in the unroute ?
In this lines

Router/Http.php

Lines 596 to 610 in af9b543

function ( Array $matches ) use ( &$id, &$variables, &$allowEmpty ) {
$m = strtolower($matches[1]);
if(!isset($variables[$m]) || '' === $variables[$m])
if(true === $allowEmpty)
return '';
else
throw new Exception(
'Variable %s is empty and it is not allowed when ' .
'unrouting rule %s.',
7, array($m, $id));
return $variables[$m];
},
I think it could be possible to extract the regexp defining the value format and make a simple test on the concerned value given to unroute
(edit: I change the source link)


Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

New context: Socket/WebSocket.

It could be cool to be able to use Hoa\router in a WebSocket context like in Http context.

Some behaviour differ like Router::getURI() and the way to return data, so there is some of work here.

thoughts?


Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

undefined function Hoa\Router\Http\mb_strtolower()

I run an Hoa application on a fresh Docker installation (official PHP:FPM) with PHP7.0.3

root@vehicle-cli:/home/scm/Data/Bin# php -v
PHP 7.0.3 (cli) (built: Feb  5 2016 18:32:47) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies

I have to active PHP extension only if needed.
I've just install mbstring.

My router is:

$router
    ->get(
        'cars',
        '/v1/cars',
        '\Application\Controller\Car',
        'indexAction'
    )
    ->get(
        'car',
        '/v1/car/(?<car_id>\d+)',
        '\Application\Controller\Car',
        'getAction'
    );

It's good while I get http://192.168.99.106:11080/v1/cars
But while I get http://192.168.99.106:11080/v1/car/123, I read:

<b>Fatal error</b>:  Uncaught Error: Call to undefined function Hoa\Router\Http\mb_strtolower() in /home/scm/vendor/hoa/router/Http/Http.php:429
Stack trace:
#0 /home/scm/vendor/hoa/dispatcher/Dispatcher.php(133): Hoa\Router\Http\Http-&gt;route()
#1 /home/scm/Application/Public/index.php(37): Hoa\Dispatcher\Dispatcher-&gt;dispatch(Object(Hoa\Router\Http\Http))

As I read mb_strtolower is available on PHP7 with mbstring extension.
Do you see something wrong?

root@vehicle-cli:/home/scm/Data/Bin# php -i | grep mb
Additional .ini files parsed => /usr/local/etc/php/conf.d/docker-php-ext-mbstring.ini
Zend Multibyte Support => provided by mbstring
xmlrpc_error_number => 0 => 0
mbstring
Multibyte string engine => libmbfl
libmbfl version => 1.3.2
mbstring extension makes use of "streamable kanji code filter and converter", which is distributed under the GNU Lesser General Public License version 2.1.
mbstring.detect_order => no value => no value
mbstring.encoding_translation => Off => Off
mbstring.func_overload => 0 => 0
mbstring.http_input => no value => no value
mbstring.http_output => no value => no value
mbstring.http_output_conv_mimetypes => ^(text/|application/xhtml\+xml) => ^(text/|application/xhtml\+xml)
mbstring.internal_encoding => no value => no value
mbstring.language => neutral => neutral
mbstring.strict_detection => Off => Off
mbstring.substitute_character => no value => no value

And I can test:

root@vehicle-cli:/home/scm/Data/Bin# php -a
Interactive shell

php > $t = "GAbuZOmeuh";
php > echo mb_strtolower($t);
gabuzomeuh

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.