Configuration and use of the SOAP protocol for YII Framework (Webservice)

Source: Internet
Author: User
Tags soap yii

Yii relies on document annotations (Doc comments) and class reflection (class reflection) to identify which methods can be called remotely, including their parameters and return values, but can only return strings at this time, cannot return an array, or "array" if the array is returned; Therefore, the return value is converted to a JSON string and returned.


1. Define service Provider, server-side file code, webservercontroller.php

<?php/****************************** * @author Sara zhou* Create time 2014-06-25 16:00:00* Yii Framework API interface side of server ( WebService-based interface server-side) * Note php.ini Open SOAP extension: Extension=php_soap.dll********************************/class Webservercontroller extends ccontroller{/** * @var Array error * @soap */public $error =array (' 0000 ' = ' operation succeeded ', ' 0001 ' =& gt; ' Operation failed ', ' 0002 ' = ' parameter param error ', ' 1001 ' = ' user not present ', ';p ublic function actions () {return array (' Approval ' =>array (' Class ' = ' cwebserviceaction ', ' Classmap ' =>array (//classmap in fact as long as the corresponding model on the line, such as here Apiuser ' Apiuser ',),);} /** * @desc Get_user_info () to obtain user information, code comments containing * @soap, this method can be accessed through soap to * @param array * @return array the Apiuser info must also and mode L Name consistent * @soap */public function get_user_info ($param _arr) {$param _arr=cjson::d ecode ($param _arr); $param [' User_name ']= Htmlspecialchars (@ $param _arr[' user_name '); $param [' request_id ']=intval (@ $param _arr[' request_id ']);// Add API access log information $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 ']);//Verify that the relevant parameters meet the requirements 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 ']);//Update API access log information $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 ']);//Update API access log information $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 ']];//Update API access log information $ Apilog->update_api_log ($log _id, @ $res, @ $res [' response_time '], @ $res [' error_code '], $res [' error_msg ']); return $res; }/* * Code comment does not contain * @soap, you cannot access the */public function test ($param _arr) {$arr = array (' user_id ' = = $param _arr[' user_id ' in soap mode)                ], ' request_id ' + $param _arr[' user_id '],//' request number ', ' request_time ' + = $param _arr[' user_id '],//' request time ' ); return true;}}


Save webservercontroller.php file, browser input address: Http://localhost/api/webServer/approval, will get a lot of XML format content, in fact, he is the above web Service-defined Wsdl.xml content, you can see the open method in the Server API interface


2. Client invocation (This instance invokes the instance for the PHP client and can be used in other languages)


<?php/****************************** * @author Sara zhou* Create time 2014-06-25 16:00:00* Yii Framework API interface End client Invocation instance ( WebService-based interface server-side) * Note php.ini Open SOAP extension: Extension=php_soap.dll********************************/class Clientcontroller extends Ccontroller{public function actiongetuserinfo () {//Make server access address $client = new soapclient ('/HTTP/ Localhost/api/webserver/approval ');//Call the Server interface method Get_user_info () to obtain user information, because the interface is a JSON array, it is transmitted in JSON format $res= $client- >get_user_info (' {' user_ame ': ' 123 ', ' request_id ': ' 23123 '} '); Var_dump ($res);}}? >




3. User model layer File user.php =

<?php/** * User Model * * @author  The variables to be exposed in Sara Zhou */class User extends Cactiverecord{//model, you need to indicate the following form/**  * @var I Nteger    user_id * @soap */public $id/** * @var string     post title * @soap */public $title;p ublic static function mo Del ($className =__class__) {return Parent::model ($className);} Public Function TableName () {return ' user ';} public static function GetUserInfo ($user _name) {    return User::model ()->findbypk ($user _name);}}
The variables to be exposed in the model need to be marked in the following form

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


4. Request the log API file for the model layer, apilog.php =

<?php/** * * @author Sara Zhou * @create 2014-06-11 * @desc: Used primarily for logging API access logs */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 () Log API request log * @param $require _no* @param $require _param*/public function Insert_api_log ($require _no, $require _param) {//do only insert $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 () Update API request log * @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) {//update only $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 calls (intercepting invocation)

By implementing the [Iwebserviceprovider] interface, all methods can be intercepted, and in [Iwebserviceprovider::beforewebmethod], this provider can acquire the current Cwebservice instance, And by Cwebservice::methodname to get the method name of the current request, it can return FALSE if the remote method should not be called for some reason (for example, unauthorized access)


6. Note:
A. Server to open the SOAP function, search for soap in Phpinfo, if it is open, there is a big title is soap
B. Classmap in fact, as long as the corresponding model on the line, such as the apiuser here.
c. In the code comment * @return apiuser[] The Apiuser records apiuser[] must also match the model name
d. In the code comments * @soap This can not be less, or can not be accessed through SOAP, I think there are so many articles in the comments
E. If a controller has accessrules, you have to set a visitor to access getpredictions ()
F. The variables to be exposed in model must be indicated in the following form:

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.