symfony裏實現resfull api

----------------------------------------------------------

注:筆記,自己摸索出來的,路子野,僅供參考。

----------------------- 歡迎指教,不勝感激。。。

<?php
// BaseController.php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class BaseController extends Controller
{
    protected static $method_type = array('get', 'post', 'put', 'patch', 'delete');

    /**
     * description: 負責restfull api調派
     * @param {request obj,class||obj,string,[array]} 
     * @return: array
     */
    public static function restfullDispatch(Request $request,$obj,$resouce,$params=null){		
        $method = strtolower($request->server->get('REQUEST_METHOD'));
        if (in_array($method, self::$method_type)) {
            //調用請求方式對應的方法
            $method_name = $method . ucfirst($resouce);
            if(!method_exists($obj,$method_name)){
                throw new Exception('The method:'.$method_name.' not exists!');
            }
            return $obj->$method_name($params);
        }
        return false;
    }
}

然後所有controller繼承BaseController,Action調$this::restfullDispatch() 就行了,最後路由類似:

get /api/user

post /api/user

put /api/user

patch /api/user

……

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章