All Projects → midned → Routy

midned / Routy

Licence: MIT license
Routing library for PHP with REST support.

Programming Languages

PHP
23972 projects - #3 most used programming language
ApacheConf
554 projects

Routy

Routing library for PHP with REST support.

License

MIT License

Installation

It's PSR-0 compatible.

You can git clone it and include src/Routy/autoload.php to autoload the classes.

And you can install it via composer

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:

<?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.

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)

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

<?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

<?php

$router->get('some', function()
{

});

$router->post('some', function()
{

});

They will handle get and post requests to http://site.com/app_context/some

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).

Example how to handle PUT and DELETE requests to http//site.com/app_context/articles:

<?php

$router->put('articles', function()
{

});

$router->delete('articles', function()
{

});

Route wildcards

Wildcards can be used to pass arguments to the function using the URL

Example:

<?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.

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

  • {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:

<?php

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

.

If you preffer to use the custom name of parameter you can extend the wildcards.

<?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.

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

Using the Routy\Action::to

Coded examples are better!:

<?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.

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

<?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.

Before filter:

<?php

$router->get('some/{num}', function($id)
{

})
->before(function($id)
{

});

The before filter will receives the same parameters as the main action do

After filter:

<?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.

When filter

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

Example:

<?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.

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:

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

Examples:

<?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.

If you want to handle all type of http errors you can ommit the first parameter.

<?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.

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)

Still working on the documentation....

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].