How can I create group routing in PHP with Closure? I'm creating my own REST API from scratch in PHP for practice and learning.
In bootstrap file i call App class:
$app = new App/App();
$app->import('routes.php');
I have routes.php file with:
$app->group('/api/v1', function() use ($app)
{
$app->group('/users', function() use ($app)
{
$app->get('/', 'User', 'index');
$app->post('/', 'User', 'post');
$app->get('/{id}', 'User', 'get');
$app->put('/{id}', 'User', 'put');
$app->delete('/{id}', 'User', 'delete');
});
});
It needs to create routes like this:
App class:
class App
{
public function group($link, Closure $closure)
{
$closure();
}
}
And it sets routes like this:
What should I do to prefix urls ? How can I "foreach" these other $app->get(), $app->post() method callings ?
Figured it out! Added DI container to App class which handles Router, Route and RouteGroup classes. PHP SLIM framework was my inspiration - https://github.com/slimphp/Slim/tree/3.x/Slim
First I call group() method from App class with calls pushGroup() method from Router class. Then I invoke RouteGroup class with $group();. After that I cal popGroup() to return only last route group.
When adding groups url to Route, just run processGroups() method in Router class to add prefix links.
App class
/**
* Route groups
*
* @param string $link
* @param Closure $closure
* @return void
*/
public function group($link, Closure $closure)
{
$group = $this->container->get('Router')->pushGroup($link, $closure);
$group();
$this->container->get('Router')->popGroup();
}
Router class
/**
* Process route groups
*
* @return string
*/
private function processGroups()
{
$link = '';
foreach ($this->route_groups as $group) {
$link .= $group->getUrl();
}
return $link;
}
/**
* Add a route group to the array
* @param string $link
* @param Closure $closure
* @return RouteGroup
*/
public function pushGroup($link, Closure $closure)
{
$group = new RouteGroup($link, $closure);
array_push($this->route_groups, $group);
return $group;
}
/**
* Removes the last route group from the array
*
* @return RouteGroup|bool The RouteGroup if successful, else False
*/
public function popGroup()
{
$group = array_pop($this->route_groups);
return ($group instanceof RouteGroup ? $group : false);
}
Route class is basic class with routing parameters - method, url, controller, action and additional parameters so I won't copy it here.
RouteGroup class
/**
* Create a new RouteGroup
*
* @param string $url
* @param Closure $closure
*/
public function __construct($url, $closure)
{
$this->url = $url;
$this->closure = $closure;
}
/**
* Invoke the group to register any Routable objects within it.
*
* @param Slinky $app The App to bind the callable to.
*/
public function __invoke()
{
$closure = $this->closure;
$closure();
}