think\Route::resource PHP Method

resource() public static method

注册资源路由
public static resource ( string $rule, string $route = '', array $option = [], array $pattern = [] ) : void
$rule string 路由规则
$route string 路由地址
$option array 路由参数
$pattern array 变量规则
return void
    public static function resource($rule, $route = '', $option = [], $pattern = [])
    {
        if (is_array($rule)) {
            foreach ($rule as $key => $val) {
                if (is_array($val)) {
                    list($val, $option, $pattern) = array_pad($val, 3, []);
                }
                self::resource($key, $val, $option, $pattern);
            }
        } else {
            if (strpos($rule, '.')) {
                // 注册嵌套资源路由
                $array = explode('.', $rule);
                $last = array_pop($array);
                $item = [];
                foreach ($array as $val) {
                    $item[] = $val . '/:' . (isset($option['var'][$val]) ? $option['var'][$val] : $val . '_id');
                }
                $rule = implode('/', $item) . '/' . $last;
            }
            // 注册资源路由
            foreach (self::$rest as $key => $val) {
                if (isset($option['only']) && !in_array($key, $option['only']) || isset($option['except']) && in_array($key, $option['except'])) {
                    continue;
                }
                if (isset($last) && strpos($val[1], ':id') && isset($option['var'][$last])) {
                    $val[1] = str_replace(':id', ':' . $option['var'][$last], $val[1]);
                } elseif (strpos($val[1], ':id') && isset($option['var'][$rule])) {
                    $val[1] = str_replace(':id', ':' . $option['var'][$rule], $val[1]);
                }
                $item = ltrim($rule . $val[1], '/');
                self::rule($item . '$', $route . '/' . $val[2], $val[0], $option, $pattern);
            }
        }
    }

Usage Example

Example #1
0
 public function testRest()
 {
     Route::rest('read', ['GET', '/:id', 'look']);
     Route::rest('create', ['GET', '/create', 'add']);
     Route::rest(['read' => ['GET', '/:id', 'look'], 'create' => ['GET', '/create', 'add']]);
     Route::resource('res', 'index/blog');
     $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'add']], Route::check('res/create'));
     $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'look']], Route::check('res/8'));
 }
All Usage Examples Of think\Route::resource