2017 © Pedro Peláez
 

library routy

Yet another php routing library

image

routy/routy

Yet another php routing library

  • Tuesday, June 28, 2016
  • by Th3-Night
  • Repository
  • 4 Watchers
  • 13 Stars
  • 30 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 2 Forks
  • 0 Open issues
  • 1 Versions
  • 0 % Grown

The README.md

Routy

Routing library for PHP with REST support., (*1)

License

MIT License, (*2)

Installation

It's PSR-0 compatible., (*3)

You can git clone it and include src/Routy/autoload.php to autoload the classes., (*4)

And you can install it via composer, (*5)

Documentation

First step


<?php require_once 'src/Routy/autoload.php'; // if installed with composer include // require_once 'vendor/autoload.php'; use Routy\Router;

Creating the router instance

Simple as the following lines:, (*6)


<?php $app = new Router();

Generating the base url

The first parameter in the constructor of the Routy\Router class is the base url. If it's null or not defined it will be generated., (*7)

The second parameter is a boolean. In case we want to include the script name in the url we will set it to true. We will set to false otherwise (and it's false by default), (*8)

The base url will be needed in the future if you want to generate absolute urls of your defined routes Examples:, (*9)


<?php $router = new Router(); $router->base(); // will return something like http://site.com/ $router = new Routy\Router(null, true); $router->base(); // will return something like http://site.com/index.php $router = new Routy\Router('http://some.net'); $router->base(); // will return http://some.net

Handle requests


<?php $router->any('/, home', function() { });

That will handle request from any request method to http://site.com/app_context/ or http://site.com/app_context/home, (*10)


<?php $router->get('some', function() { }); $router->post('some', function() { });

They will handle get and post requests to http://site.com/app_context/some, (*11)

RESTful

You can handle PUT and DELETE requests. But you have to include a hidden field in your html form, something like <input type="hidden" name="_method" value="put" /> (the same with DELETE method)., (*12)

Example how to handle PUT and DELETE requests to http//site.com/app_context/articles:, (*13)


<?php $router->put('articles', function() { }); $router->delete('articles', function() { });

Route wildcards

Wildcards can be used to pass arguments to the function using the URL, (*14)

Example:, (*15)


<?php $router->get('articles/{id}', function($id) { echo "Article {$id}"; });

When you go to http://site.com/app_context/articles/1 you will see "Article 1". But, you also can make the url like http://site.com/app_context/articles/test and you will see "Article test", that's a problem., (*16)

But, there's a list of default wildcards to use and validate them., (*17)

  • {any}
    • Will match any character.
    • Regex: (.+)
  • {alnum}
    • Will match alphabetic characters and numbers.
    • Regex: ([[:alnum:]]+)
  • {num}
    • Will match any number.
    • Regex: ([[:digit:]]+)
  • {alpha}
    • Will match alphabetic characters.
    • Regex: ([[:alpha:]]+)
  • {segment}
    • Will match uri segments (everything except /).
    • Regex: ([^/]*)

Then you want a valid id for the "article" your code must be something like:, (*18)


<?php $router->get('articles/{num}', function($id) { echo "Article {$id}"; });

., (*19)

If you preffer to use the custom name of parameter you can extend the wildcards., (*20)


<?php use Routy\Wildcards; Wildcards::extend('id', '{num}'); // This way you will have an alias to the {num} wildcard Wildcards::extend('some', '(...)'); // And this way you will have a {some} wildcard with the "(...)" regular expression

Named Routes

You can use named routes to make easy the way you generate your urls., (*21)

You can generate routes passing arguments to them, like creating a url for a blog entry or something like that., (*22)

Using the Routy\Action::to, (*23)

Coded examples are better!:, (*24)


<?php $router->get('/', function() use(&$router) { $arguments = array('id' => 2); echo 'Home page<br />'; echo 'Generate a route to "users/2": '; echo $router->to('users', $arguments); // The first parameter is the route name and the second the values to replace })->named('home'); // here we identify this route with the "home" name // We can also use a object to the replacements $router->get('example2', function() use(&$router) { $user = new StdClass(); // Like if we fetched it from the database $user->id = 2; echo 'Generate a route to "users/2" using an object: '; echo $router->to('users', $user); // Will obtain the varibles of the object and replace the values, like it did before }); $router->get('users/{id}', function($id) use(&$router) { echo 'Id: ' . $id . '<br />'; echo 'Home link: '; echo $router->to('home'); })->named('users'); // and this one with "users"

Simple as that., (*25)

If the first parameter, the route name doesn't match with any defined route, we will generate an absolute url with it., (*26)


<?php $router->get('/', function() use(&$router) { echo $router->to('some/url'); // will return something like http://site.host/some/url });

Before & After filters

You can execute a callback before or after the main action., (*27)

Before filter:, (*28)


<?php $router->get('some/{num}', function($id) { }) ->before(function($id) { });

The before filter will receives the same parameters as the main action do, (*29)

After filter:, (*30)


<?php $router->get('some/{num}', function($id) { return "Selected id {$id}"; }) ->after(function($response) { });

The after filter will receive the returned value of the main action. In this case it will receive "Selected id 1" if we go to http://site.com/app_context/some/1., (*31)

When filter

The when filter is executed before the main action, if it returns true we'll continue the execution, otherwise we'll stop., (*32)

Example:, (*33)


<?php $router->get('when/{num}', function($num) { echo "Selected number: {$num}"; }) ->when(function($num) { return $num == 2; });

Then if you go to http://site.com/app_context/2 you will receive an http not found error (later we'll handle them) and you will see "Selected number: (selected one)" when the number isn't 2., (*34)

Throwing http errors

Sometimes you want to throw a http error for some reason like a record in the database that was not found or something like that, to do that exists the Router::produce method. Example:, (*35)

$router->get('user/{num}', function($id) use(&$router) // use the router global variable
{
    // some code to fetch the user

    if (!$user) // if the user doesn't exist in the database
    {
        $router->produce(404);
    }

    // your code
});

Error handler

When the current URL doesn't correspond to any defined route we'll throw a Routy\HttpException. With the code of the error (404)., (*36)

Examples:, (*37)


<?php $router->error($error_code = 404, function($error) // the $error variable is the thrown exception { });

With this you will handle all http errors with the 404 error code., (*38)

If you want to handle all type of http errors you can ommit the first parameter., (*39)


<?php $router->error(function() { });

If we already defined a handler for an http error type the second example will handle all type of errors except the defined one., (*40)

The .htaccess file

You can hide the script name in the uri file using, for example, a .htaccess (like the example one on this repo), (*41)

Still working on the documentation....

The Versions

28/06 2016

dev-master

9999999-dev

Yet another php routing library

  Sources   Download

MIT

The Requires

  • php >=5.3.0

 

php routing routy