thinkphp5 资源路由的创建及使用

注意:(在使用资源控制器时,尽量隐藏入口文件  )

在根目录/pubilc/.htaccess 放入以下代码:


  Options +FollowSymlinks -Multiviews
  RewriteEngine On

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php?/$1 [QSA,PT,L]

 ① 创建api模块

php think build --module api

 ② 创建news控制器

php think make:controller api/News
③ 设置路由(application/route.php)
\think\Route::resource('news','api/news');
相当于分别设置了以下路由:
\think\Route::get('news','api/news/index');
\think\Route::get('news/create','api/news/create');
\think\Route::post('news','api/news/save');
\think\Route::get('news/:id','api/news/read');
\think\Route::get('news/:id/edit','api/news/edit');
\think\Route::put('news/:id','api/news/update');
\think\Route::delete('news/:id','api/news/delete');
设置后会自动注册7个路由规则,如下:

thinkphp5 资源路由的创建及使用_第1张图片

④ 修改News控制器,返回json格式数据

 200, 'msg' => 'success', 'data'=>'index']);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        return json(['code' => 200, 'msg' => 'success', 'data'=>'create']);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        return json(['code' => 200, 'msg' => 'success', 'data'=>'save']);
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        return json(['code' => 200, 'msg' => 'success', 'data'=>'read']);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        return json(['code' => 200, 'msg' => 'success', 'data'=>'edit']);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        return json(['code' => 200, 'msg' => 'success', 'data'=>'update']);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        return json(['code' => 200, 'msg' => 'success', 'data'=>'delete']);
    }
}

 通过postman 分别访问以下七个地址:

请求方式	 请求地址
get			http://www.tpshop.com/news
get			http://www.tpshop.com/news/create
post		http://www.tpshop.com/news
get			http://www.tpshop.com/news/33
get			http://www.tpshop.com/news/33/edit
put			http://www.tpshop.com/news/33
delete		http://www.tpshop.com/news/33
public目录下,创建测试文件 api.html



    
    ajax请求restful接口
    











 

 

 

 

你可能感兴趣的:(Thinkphp5.0,php,thinkphp)