YII架構之soap協議的配置跟使用(Webservice)

來源:互聯網
上載者:User

標籤:yii中soap   webservice介面   api介面的伺服器端及用戶端   

Yii依靠文檔註解(doc comments)和類反射(class reflection)來識別哪個方法可以被遠程調用,包括他們的參數和返回值,但目前只能返回字串,不能返回數組,若返回數組,則為"array";故我將返回值轉換為json字串再返回.


1. 定義Service Provider,伺服器端檔案代碼,WebServerController.php

<?php/****************************** * @author sara zhou* create time 2014-06-25 16:00:00* YII架構API介面端的server (基於Webservice的介面伺服器端)* 注意php.ini開啟soap擴充:extension=php_soap.dll********************************/class WebServerController extends CController{/** * @var array error * @soap */public $error=array('0000'=>'操作成功','0001'=>'操作失敗','0002'=>'參數param錯誤','1001'=>'使用者不存在',);public function actions(){return array('approval'=>array('class'=>'CWebServiceAction','classMap'=>array(//classMap其實只要是對應的Model就行,比如這裡的ApiUser'ApiUser',  ),),);}/** * @desc get_user_info()擷取使用者資訊,代碼注釋裡包含 * @soap,則 此方法可通過soap訪問到 * @param array * @return array the ApiUser info 也必須和Model名稱一致 * @soap */public function get_user_info($param_arr){$param_arr=CJSON::decode($param_arr);$param['user_name']=htmlspecialchars(@$param_arr['user_name']);$param['request_id']=intval(@$param_arr['request_id']);//添加API訪問日誌資訊$apiLog=new ApiLog1();$log_id=$apiLog->insert_api_log($param['request_id'], CJSON::encode($param));$res=array('user_name'=>$param['user_name'],'user_email'=>$param['user_email']);//驗證相關參數是否符合要求if (empty($param['user_name'])) {$res['response_time']=date("YmdHis");$res['error_code']='0002';$res['error_msg']=str_replace('param','user_name',$this->error['0002']);//更新API訪問日誌資訊$apiLog->update_api_log($log_id, CJSON::encode($res),@$res['response_time'], @$res['error_code'],$res['error_msg']);return CJSON::encode($res);}if ($param['request_id']<=0) {$res['response_time']=date("YmdHis");$res['error_code']='0002';$res['error_msg']=str_replace('param','request_id',$this->error['0002']);//更新API訪問日誌資訊$apiLog->update_api_log($log_id, @$res,@$res['response_time'], @$res['error_code'],$res['error_msg']);return $res;}$user=new User();$user_info=$user->getUserInfo($param['user_name']);if ($user_info){$res['error_code']="1003";}else {$res['error_code']="0000";}$res['response_time']=date("YmdHis");$res['error_msg']=$this->error[$res['error_code']];//更新API訪問日誌資訊$apiLog->update_api_log($log_id, @$res,@$res['response_time'], @$res['error_code'],$res['error_msg']);return $res; }/* * 代碼注釋裡不包含 * @soap,則無法通過soap方式訪問 */public function test($param_arr){$arr =  array('user_id'=>$param_arr['user_id'],    'request_id'=>$param_arr['user_id'],//'請求號',    'request_time'=>$param_arr['user_id'],//'請求時間'                );return true;}}


儲存WebServerController.php檔案,瀏覽器輸入地址:http://localhost/api/webServer/approval,將得到一個包含大量XML格式的內容,實際上他就是上面Web Service定義的WSDL.XML內容中,可以看到伺服器API介面中開放的方法


2.用戶端調用(此執行個體為php用戶端調用執行個體,可使用其他語言)


<?php/****************************** * @author sara zhou* create time 2014-06-25 16:00:00* YII架構API介面端的用戶端調用執行個體 (基於Webservice的介面伺服器端)* 注意php.ini開啟soap擴充:extension=php_soap.dll********************************/class ClientController extends CController{public function actionGetUserInfo(){//制定伺服器訪問地址$client = new SoapClient('http://localhost/api/webServer/approval');//調用伺服器介面方法 get_user_info()擷取使用者資訊;由於介面是傳json數組,故這裡以傳json格式傳遞$res= $client->get_user_info('{"user_ame":"123","request_id":"23123"}');var_dump($res);}}?>




3.使用者模型層檔案 User.php => model

 

<?php/** * 使用者模型 * * @author Sara Zhou  */ class User extends CActiveRecord{//Model裡要公開的變數,需要用下面的形式標明/**  * @var integer    user_id * @soap */public $id;/** * @var string     post title * @soap */public $title;public static function model($className=__CLASS__){return parent::model($className);}public function tableName(){return 'user';}public static function getUserInfo($user_name){    return User::model()->findbyPk($user_name);} }
model裡要公開的變數,需要用下面的形式標明

/** 
* @var integer    user_id
* @soap
*/
public $id;


4.請求模型層的日誌API檔案,ApiLog.php  => model

<?php/** *  * @author Sara zhou * @create 2014-06-11 * @desc:主要用於記錄API訪問日誌 */class ApiLog extends CActiveRecord{public static function model($className=__CLASS__){return parent::model($className);}/** * @return string the associated database table name */public function tableName(){return 'api_log';}/* * insert_api_log()記錄API請求日誌* @param $require_no* @param $require_param*/public function insert_api_log($require_no,$require_param){//只做插入$binsd = array('require_no'=> $require_no,'require_url'=> $_SERVER['HTTP_HOST'] .$_SERVER['REQUEST_URI'],'require_param'=> $require_param,'require_time'=> date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']),'require_method'=> $_SERVER['REQUEST_METHOD'],'server_protocol'=> $_SERVER['SERVER_PROTOCOL'],'create_time'=> date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']),);if ($_SERVER["HTTP_X_FORWARDED_FOR"]==""){$bind['require_ip']=$_SERVER['REMOTE_ADDR'] .':'.$_SERVER['REMOTE_PORT'];}else$bind['require_ip']=$_SERVER["HTTP_X_FORWARDED_FOR"].':'.$_SERVER['REMOTE_PORT'];$this->setAttributes($binsd, false);$this->save();return $this->attributes['id'];}/* * update_api_log()更新API請求日誌* @param $log_id* @param $response_param* @param $response_time* @param $error_code* @param $error_msg*/public function update_api_log($log_id,$response_param,$response_time,$error_code,$error_msg){//只做更新$sql = "UPDATE api_log set response_param=:response_param,response_time=:response_time,error_code=:error_code,error_msg=:error_msg where id=:id";$command=Yii::app()->db->createCommand($sql);$bind = array('id'=> $log_id,'response_param'=> $response_param,'response_time'=> $response_time,'error_code'=> $error_code,'error_msg'=> $error_msg,);return $command->execute($bind);}}


5.攔截遠程方法調用(Intercepting Remote Method Invocation) 

通過實現[IWebServiceProvider]介面,可以攔截所有方法,在[IWebServiceProvider::beforeWebMethod],這個provider可以擷取當前CWebService執行個體,並通過CWebService::methodName來擷取當前請求的方法名,它可以返回false,如果這個遠程方法因某些原因(比如未經授權的訪問)不應被調用


6.注意:
a. 伺服器要開啟soap功能,在phpinfo裡搜soap,如果已經開啟了的話有個大標題就是SOAP
b. classMap其實只要是對應的Model就行,比如這裡的ApiUser。
c. 代碼注釋裡* @return ApiUser[] the apiUser records ApiUser[]也必須和Model名稱一致
d. 代碼注釋裡* @soap 這個也不能少,不然無法通過soap方式訪問,想不到注釋裡還有這麼多文章
e. 如果controller裡有accessRules的話,得設定訪客就可以訪問getPredictions()
f. Model裡要公開的變數,需要用下面的形式標明:

/**
     * @var integer UID of this record
     * @soap
     */
    public $uid;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.