Skip to content

Instantly share code, notes, and snippets.

@victorknust
Created December 26, 2016 18:50
Show Gist options
  • Save victorknust/4540f90648d7e5a1654454548e5461dc to your computer and use it in GitHub Desktop.
Save victorknust/4540f90648d7e5a1654454548e5461dc to your computer and use it in GitHub Desktop.
<?php
class Router
{
public $routes = array();
public function route( $method, $pattern, $callback )
{
$pattern = '/^' . str_replace( array('/', ':id'), array('\/', '([0-9]+)'), $pattern ) . '$/';
$this->routes[$method][$pattern] = $callback;
}
public function execute( $uri, $method )
{
foreach ( $this->routes[$method] as $pattern => $callback ) {
if ( preg_match( $pattern, $uri, $params ) ) {
array_shift( $params );
if ( is_string( $callback ) && strpos( $callback, '@' ) ) {
list( $controller, $method ) = explode( '@', $callback );
return call_user_func_array( array(new $controller, $method), array_values( $params ) );
}
return call_user_func_array( $callback, array_values( $params ) );
}
}
}
public function __call($method, $arguments)
{
list( $pattern, $callback ) = $arguments;
$this->route( strtoupper($method), $pattern, $callback );
}
}
//-------------------------------------------------------------------
class User {
public function __construct() {
}
public function profile ( $id ) {
echo "Exibir perfil do usuário id: $id";
}
}
//-------------------------------------------------------------------
$r = new Router();
$r->get( 'usuario/:id/perfil', 'User@profile');
$r->post( 'usuario/:id/perfil', 'User@profile');
$r->put( 'usuario/:id/perfil', 'User@profile');
$r->delete( 'usuario/:id/perfil', 'User@profile');
$r->execute( 'usuario/2/perfil', 'GET');
echo '<pre>';
print_r($r->routes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment