资源路由

  1. 资源路由,采用固定的常用方法来实现简化 URL 的功能;
    2. 系统提供了一个命令,方便开发者快速生成一个资源控制器;
    1. php think make:controller index/Blog
  2. 模块/控制器,默认在 controller 目录下,根据你的情况调整路径结构;
    1. php think make:controller Blog
    2. //单应用
    3. php think make:controller ../index/controller/Blog //多应用
  3. 模块/控制器,默认在 controller 目录下,根据你的情况调整路径结构;
    5. 从生成的多个方法,包含了显示、增删改查等多个操作方法;
    6. 在路由 route.php 文件下创建一个资源路由,资源名称可自定义;
    1. Route::resource('blog', 'Blog');
    2. //多应用即:index/Blog
  4. 这里的 blog 表示资源规则名,Blog 表示路由的访问路径;
    8. 资源路由注册成功后,会自动提供以下方法,无须手动注册;
    9. GET 访问模式下:index(blog),create(blog/create),read(blog/:id) edit(blog/:id/edit)
    10. POST 访问模式下:save(blog);
    11. PUT 方式模式下:update(blog/:id);
    12. DELETE 方式模式下:delete(blog/:id);
    1. http://localhost:8000/blog/
    2. (index)
    3. http://localhost:8000/blog/5
    4. (read)
    5. http://localhost:8000/blog/5/edit (edit)
  5. 对于 POST,是新增,一般是表单的 POST 提交,而 PUT 和 DELETE 用 AJAX 访问;
    14. 将跨域提交那个例子修改成.ajax,其中 type 设置为 DELETE 即可访问到;
    1. $.ajax({
    2. type : "DELETE",
    3. url : "http://localhost:8000/blog/10",
    4. success : function (res) {
    5. console.log(res);
    6. }
    7. });
  6. 默认的参数采用 id 名称,如果你想别的,比如:blog_id,则:
    1. ->vars(['blog'=>'blog_id']);
    2. //相应的 delete($blog_id)
  7. 也可以通过 only()方法限定系统提供的资源方法,比如:
    1. ->only(['index','save','create'])
  8. 还可以通过 except()方法排除系统提供的资源方法,比如:
    1. ->except(['read','delete','update'])
  9. 使用 rest()方法,更改系统给予的默认方法,1.请求方式;2.地址;3.操作;
    1. Route::rest('create', ['GET', '/:id/add', 'add']);
    2. //批量
    3. Route::rest([
    4. 'save' => ['POST', '', 'store'],
    5. 'update' => ['PUT', '/:id', 'save'],
    6. 'delete' => ['DELETE', '/:id', 'destory'],
    7. ]);
  10. 使用嵌套资源路由,可以让上级资源对下级资源进行操作,创建 Comment 资源;
    1. class Comment {
    2. public function read($id, $blog_id)
    3. {
    4. return 'Comment id:'.$id.',Blog id:'.$blog_id;
    5. }
    6. public function edit($id, $blog_id)
    7. {
    8. return 'Comment id:'.$id.',Blog id:'.$blog_id;
    9. }
    10. }
  11. 使用嵌套资源路由,可以让上级资源对下级资源进行操作,创建 Comment 资源;
    1. Route::resource('blog.comment', 'Comment');
  12. 资源嵌套生成的路由规则如下:
    1. http://localhost:8000/blog/:blog_id/comment/:id
    2. http://localhost:8000/blog/:blog_id/comment/:id/edit
  13. 嵌套资源生成的上级资源默认 id 为:blog_id,可以通过 vars 更改;
    1. Route::resource('blog.comment', 'Comment')
    2. ->vars(['blog'=>'blogid']);