• Yii 实现restful


    首先做一下接口的 URL 规划,假设我们要面对的资源是 item ,现在我们暴露5个接口供其他应用调用,分别是:

    对于所有 item 列表调用: GET /rest/item
    对于某个 item 信息调用: GET /rest/item/(d+)
    创建一个 item: POST /rest/item
    更新一个 item: PUT /rest/item/(d+)
    删除一个 item: DELETE /rest/item/(d+)
    'urlManager'=>array(
                'urlFormat'=>'path',
                'rules'=>array(
                  
                    //restful routers
                 
                    array('rest/list','pattern'=>'rest/item','verb'=>'GET'),
                    array('rest/view','pattern'=>'rest/item/<id:d+>','verb'=>'GET'),
                    array('rest/create','pattern'=>'rest/item','verb'=>'POST'),
                    array('rest/update','pattern'=>'rest/item/<id:d+>','verb'=>'PUT'),
                    array('rest/delete','pattern'=>'rest/item/<id:d+>','verb'=>'GET'),
                
                ),
            ),
             

    url配置请看:http://www.cnblogs.com/youxin/p/3870547.html

    http://www.cnblogs.com/jshen/p/3732193.html

    然后开始编写 REST 的 Controller,安装 yii 框架的约定,我们建立 protected/controllers/RestController.php ,文件内容结构如下:

    class RestController extends Controller
    {
      // Actions
      public function actionList()
      {
      }
      public function actionView()
      {
      }
      public function actionCreate()
      {
      }
      public function actionUpdate()
      {
      }
      public function actionDelete()
      {
      }
      // Assistant Functions
      private function _sendResponse()
      {
      }
      private function _getStatusCodeMessage()
      {
      }
    }

    实现:

    <?php
    class RestController extends Controller
    {
        //actions
        public function actionList()
        {
            $items=Post::model()->findAll();//返回的是CActiveRecord[] 
            if(empty($items))
            {
                $this->_sendResponse(200,"No items");
            }
            else
            {
                $rows=array();
                foreach($items as $item)
                {
                    $rows[]=$item->attributes;//attributes         Returns all column attribute values.
                }
                $this->_sendResponse(200,CJson::encode($rows));
            }
            
        }
        public function actionView()
        {
            if(!isset($_GET['id']))
            {
                $this->_sendResponse(500,"Item Id is missing");
            }
            $item=Post::model()->findByPk($_GET['id']);
            if(is_null($item))
                $this->_sendResponse(404,"No item");
            else
                $this->_sendResponse(200,CJson::encode($item->attributes));
            
        }
        public function actionCreate()
        {
            $item=new Post();
            foreach($_POST as $var=>$value)
            {
                if($item->hasAttribute($var))
                    $item->$var=$value;
                else 
                    $this->_sendResponse(500,"Paramter Error");
            }
                if($item->save())
                    $this->_sendResponse(200,CJson::encode($item));
                else 
                    $this->_sendResponse(500,"Could not create Item");
         
            
        }
        public function actionUpdate()
        {
             //获取 put 方法所带来的 json 数据
          $json = file_get_contents('php://input');
          $put_vars = CJSON::decode($json,true);
         
          $item = Post::model()->findByPk($_GET['id']); 
          
          if(is_null($item))
            $this->_sendResponse(400, 'No Item found');
        
          foreach($put_vars as $var=>$value) 
          {
            if($item->hasAttribute($var))
              $item->$var = $value;
            else 
              $this->_sendResponse(500, 'Parameter Error');
          }
        
          if($item->save())
            $this->_sendResponse(200, CJson::encode($item));
          else
            $this->_sendResponse(500, 'Could not Update Item');
        }
        
        public function actionDelete()
        {
          $item = Post::model()->findByPk($_GET['id']);
          if(is_null($item))
            $this->_sendResponse(400, 'No Item found');
          if($item->delete())
            $this->_sendResponse(200, 'Delete Success');
          else
            $this->_sendResponse(500, 'Could not Delete Item');
        }
            
        private function _sendResponse($status,$body='',$content_type='text/html')
        {
            $status_header='HTTP/1.1 '.$status.' '.$this->_getStatusCodeMessage($status);
            header($status_header);
            header("Content-type: ".$content_type);
            echo $body;
            Yii::app()->end();
        }
        private function _getStatusCodeMessage($status)
        {
          $codes = array(
     200=> 'OK',
                400 => 'Bad Request',
                401 => 'Unauthorized',
                402 => 'Payment Required',
                403 => 'Forbidden',
                404 => 'Not Found',
                500 => 'Internal Server Error',
                501 => 'Not Implemented', );
         
          return (isset($codes[$status])) ? $codes[$status] : '';
        }
        
    }

    上面参考下面2篇文章:

    http://www.nonb.cn/blog/yii-rest.html

    http://www.cnblogs.com/ziyouchutuwenwu/p/3436415.html

    http://www.yiiframework.com/forum/index.php?/topic/18412-new-yii-rest-tutorial/

    http://stackoverflow.com/questions/6427904/restful-server-design-in-yii

    http://www.yiiwiki.com/post/38

    http://blog.csdn.net/myweishanli/article/details/17475397

  • 相关阅读:
    zabbix增加手机短信、邮件监控的注意要点,SSL邮件发送python脚本
    关于门诊保险你需要知道的事情(原创)
    儿童做家务年龄对照表,80%的父母都后悔看晚了…
    宁65年产权公寓值得投资吗?大数据帮你分析
    为什么百万医疗险越来越多,到底选哪款?
    python 爬虫 scrapy1_官网教程
    自然语言10_分类与标注
    自然语言9_NLTK计算中文高频词
    自然语言8_中文搜词
    自然语言7_NLTK中文语料库sinica_treebank
  • 原文地址:https://www.cnblogs.com/youxin/p/3866656.html
Copyright © 2020-2023  润新知