PHP code example of sidvind / php-routes

1. Go to this page and download the library: Download sidvind/php-routes library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sidvind / php-routes example snippets



/* basic routes */
$get('foo', ['to' => 'MyController#foo']);
$post('bar/:id/baz', ['to' => 'MyController#update']); /* use :var for variables */

/* automatically setup RESTful routes */
$resource('article', [], function($r){
  $r->members(function($r){
    $r->patch('frobnicate'); /* maps to PATCH /article/:id/frobnicate */
  });
  $r->collection(function($r){
    $r->patch('twiddle'); /* maps to PATCH /article/twiddle */
  });
});

/* scoping */
$scope(':lang', [], function($r){
  $r->get('barney'); /* maps to GET /:lang/barney */
});


class Dispatcher extends Sidvind\PHPRoutes\Router {
	public function dispatch($url, $method){
		if ( $match = $this->match($url, $method) ){
			$class = "{$match->controller}Controller";
			$controller = new $class();
			return call_user_func_array([$controller, $match->action], $match->args);
		} else {
		  /* 404 */
		}
	}
}
$router = new Dispatcher('routes.php');
$router->dispatch($url, $method);

# bin/php-routes routes.php
        GET    /foo             MyController#foo      #^/foo(?P<format>\.\w+)?$#
        POST   /bar/:id/baz     MyController#update   #^/bar/(?P<id>[A-Za-z0-9\-_\.]+)/baz(?P<format>\.\w+)?$#
article GET    /article         Article#list          #^/article(?P<format>\.\w+)?$#
...
# bin/php-routes routes.php get /foo
Controller: MyController
Action: foo
Format:
Arguments:
[]
# bin/php-routes routes.php get /bar
bin/php-routes: url doesn't match any route.