// Define a routing rule $router->add('/user/:id', 'UserController@show'); // Convert a URL to a controller method $route = $router->toRoute('/user/123'); // $route will contain: array('controller' => 'UserController', 'action' => 'show', 'params' => array('id' => '123'))
// Define a routing rule with an optional parameter $router->add('/blog/:year/:month/:day/:slug?', 'BlogController@show'); // Convert a URL to a controller method $route1 = $router->toRoute('/blog/2020/04/01/hello-world'); $route2 = $router->toRoute('/blog/2020/04/01'); // $route1 will contain: array('controller' => 'BlogController', 'action' => 'show', 'params' => array('year' => '2020', 'month' => '04', 'day' => '01', 'slug' => 'hello-world')) // $route2 will contain: array('controller' => 'BlogController', 'action' => 'show', 'params' => array('year' => '2020', 'month' => '04', 'day' => '01'))This example sets up a routing rule for a blog post URL that includes an optional slug parameter. The toRoute method is called twice, once with a complete URL including a slug and once without a slug. The resulting arrays include the controller and action names as well as any parameters passed in the URL, with or without the optional parameter. Package Library: The package library used in the above example is likely to be a routing framework, such as Slim or Phalcon, which provide a built-in toRoute method to simplify URL routing in web applications.