如何使用Closure在PHP中创建组路由?我正在PHP中从头开始创建自己的REST API,用于练习和学习。
在bootstrap文件中,我调用 App 类:
$app = new App/App();
$app->import('routes.php');
我的routes.php文件包含:
$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');
});
});
需要创建这样的路线:
App类:
class App
{
public function group($link, Closure $closure)
{
$closure();
}
}
它设置了这样的路线:
我应该如何为网址添加前缀?我怎样才能" foreach"这些其他$ app-> get(),$ app-> post()方法调用?
答案 0 :(得分:1)
想出来!将DI容器添加到处理Router,Route和RouteGroup类的App类。 PHP SLIM框架是我的灵感 - https://github.com/slimphp/Slim/tree/3.x/Slim
首先,我从App类调用group()方法,并使用来自Router类的调用pushGroup()方法。然后我用$ group();调用RouteGroup类。之后我调用popGroup()返回最后一个路由组。
将组url添加到Route时,只需在Router类中运行processGroups()方法即可添加前缀链接。
应用类
/**
* 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();
}
路由器类
/**
* 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);
}
路由类是带有路由参数的基本类 - 方法,网址,控制器,操作和其他参数,所以我不会在这里复制它。
RouteGroup 类
/**
* 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();
}