Restful
Biny也同时支持restful协议的请求,可以在Action类中将$restApi
置为true
,则该Action会以restful的协议来解析路由
namespace app\controller;/** * restful演示 * @property \app\dao\userDAO $userDAO */ class restActionextends baseAction- {
// 该action以restful协议解析路由 protected $restApi =true ;// [GET] http://www.billge.cc/rest/?id=xxx public function GET_index ($id )- {
$user =$this ->userDAO ->filter (['id' =>$id ])->find ();return $user ?$this ->correct ($user ) :$this ->error ('user not found' );- }
// [POST] http://www.billge.cc/rest/test public function POST_test ()- {
$user =$this ->param ('user' );$user_id =$this ->userDAO ->add ($user );return $user_id ?$this ->correct ($user ) :$this ->error ('data error' );- }
// [PUT] http://www.billge.cc/rest/?id=xxx public function PUT_index ($id )- {
$user =$this ->param ('user' );$ret =$this ->userDAO ->filter (['id' =>$id ])->update ($user );return $ret ?$this ->correct () :$this ->error ('data error' );- }
// [PATCH] http://www.billge.cc/rest/test?id=xxx public function PATCH_test ($id )- {
$sets =$this ->param ('sets' );$ret =$this ->userDAO ->filter (['id' =>$id ])->update ($sets );return $ret ?$this ->correct () :$this ->error ('data error' );- }
// [DELETE] http://www.billge.cc/rest/test?id=xxx public function DELETE_test ($id )- {
$ret =$this ->userDAO ->filter (['id' =>$id ])->delete ();return $ret ?$this ->correct () :$this ->error ('data error' );- }
- }
同样,restful协议也可以通过自定义路由的模式来配置,例如
/config/config.php 'routeRule' =>array (// rest/(\d+) 的restful路由会自动转发到restAction中的 {method}_test方法 ' =>rest /<id :\d+>''rest/test' ,// 匹配的参数可在转发路由中动态使用 ' =>v <version :\d+>/rest/<id :\d+>/<method :[\w_]+>''rest/< ,method >'- ),
/app/controller/restAction.php // [DELETE] http://www.billge.cc/v2/rest/123/person public function DELETE_person ($version ,$id )- {
echo $version ;// 2 echo $id ;// 123 - }
// [PUT] http://www.billge.cc/rest/272 正则匹配的内容会传入方法 public function PUT_test ($id )- {
echo $id ;// 272 - }