繁体   English   中英

在PHP中使用Closure创建组路由

[英]Create group route with Closure in PHP

如何使用Closure在PHP中创建组路由? 我正在用PHP从头开始创建自己的REST API,以进行练习和学习。

在引导文件中,我调用App类:

$app = new App/App();
$app->import('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');
    });
});

它需要创建这样的路由:

  • / API / V1 /用户/
  • / API / V1 /用户/
  • / API / V1 /用户/ {ID}
  • / API / V1 /用户/ {ID}
  • / API / V1 /用户/ {ID}

应用类别:

class App
{
    public function group($link, Closure $closure)
    {
        $closure();
    }
}

并设置如下路线:

  • /
  • /
  • /{ID}
  • /{ID}
  • /{ID}

我该如何给网址加上前缀? 我如何“ foreach”其他$ app-> get(),$ app-> post()方法调用?

弄清楚了! 将DI容器添加到处理路由器,路由和路由组类的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);
}

路由类是具有路由参数的基本类-方法,URL,控制器,操作和其他参数,因此在此不再赘述。

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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM