Yii Framework Official Guide Series 47--topic: Web Service

Source: Internet
Author: User
Tags yii



Web Service is a software system designed to support mutual access between computers across networks. In a Web application, it typically uses a set of APIs that can be accessed by the Internet and executed by the requested service on the remote system host. The services required by the system host. For example, a flex-based client might invoke a function to implement a Web application that runs PHP on the server side. Web service relies on soap as the base layer of the communication protocol stack.

Yii provides Cwebservice and cwebserviceaction simplifies the implementation of Web service in Web applications. These APIs are implemented in the form of classes, called service providers. Yii will generate a WSDL for each class that describes what API is valid and how the client invokes it. When the client invokes Api,yii, it instantiates the corresponding service provider and invokes the requested API to complete the request.

Note: Cwebservice relies on php SOAP extension. Make sure that you allow this extension before you try the examples in this section.

1. Defining service Provider (define service Provider)

As we have described above, service provider is a method that a class definition can be invoked remotely. Yii relies on Doc comment and class reflection to identify which methods can be called remotely and their parameters and return values.

Let's start with a simple stock quote service. This service allows the client to request a quote for a specified stock. We determine the service provider as follows. Note that we define the provided class for the extended Ccontroller StockController . This is not required. We'll explain why we're doing this right now.


Class Stockcontroller extends ccontroller{    /**     * @param string The symbol of the stock     * @return float the Sto CK Price     * @soap     *    /Public Function GetPrice ($symbol)    {        $prices =array (' IBM ' =>100, ' GOOGLE ' = >350);        return Isset ($prices [$symbol])? $prices [$symbol]:0;        ... return stock price for $symbol    }}

In the above, we @soap declare the getPrice method as a Web service API through the label in the document comment. relies on document annotations to specify input parameter data types and return values. Other APIs can be declared in a similar way.

2. Declaring Web Service action (define Web service actions)

Service provider has been defined and we enable him to access it through the client. In particular, we want to create a controller action to expose this service. It is easy to do this by defining a cwebserviceaction action in the controller class. For our example, we put it in StockController .


Class Stockcontroller extends ccontroller{public    function actions ()    {        return array (            ' quote ' = Array (                ' class ' = ' cwebserviceaction ',            ),        );    }    /**     * @param string The symbol of the stock     * @return float the stock price     * @soap     */Public    func tion GetPrice ($symbol)    {        //...return stock price for $symbol    }}

This is the web service! we need to build If we try to access the action URL http://www.php.cn/ , we'll see a lot of XML content, which is actually a WSDL description of the Web service we've defined.

Tip: By default, Cwebserviceaction assumes that the current controller is service provider. This is because we define the getPrice method in StockController .

3. Consuming Web Service (consumer Web service)

To complete this example, let's create a client to consume the Web service we just created. The client in the example is written in PHP, but can be written in a different language, for example, and Java C# Flex so on.


$client =new soapclient (' http://hostname/path/to/index.php?r=stock/quote '); Echo $client->getprice (' GOOGLE ');

Run the above script in the Web page or in console mode and we will see GOOGLE the price 350 .

4. Data Types (datatype)

When the defined methods and properties are accessed remotely, we need to specify the data type of the input and output parameters. The following raw data types can be used:

    • Str/string: Correspondence xsd:string ;

    • Int/integer: Correspondence xsd:int ;

    • Float/double: Correspondence xsd:float ;

    • Bool/boolean: Correspondence xsd:boolean ;

    • Date: Correspondence xsd:date ;

    • Time: Correspondence xsd:time ;

    • DateTime: Correspondence xsd:dateTime ;

    • Array: Correspondence xsd:string ;

    • Object: Correspondence xsd:struct ;

    • Mixed: corresponding xsd:anyType .

If the type does not belong to any of the above primitive types, it is considered to be a compound composed of properties. A composite type is considered a class, and his attributes are used as public member variables of the class, and are marked in the document comments @soap .

We can also use the array type by attaching [] to the back of the primitive or compound type. This defines an array of the specified type.

Here is an example of defining a getPosts Web page API that returns an Post array of objects.


Class Postcontroller extends ccontroller{    /**     * @return post[] A list of posts     * @soap     */Public    func tion getposts ()    {        return Post::model ()->findall ();}    } Class Post extends cactiverecord{    /**     * @var integer post ID     * @soap */public    $id;    /**     * @var string post title     * @soap */public    $title;}

5. Class Mapping (Classes map)

In order to get compound parameters from the client, the application needs to define the mappings from the WSDL type to the corresponding PHP class. This is done by configuring the Cwebserviceaction property Classmap.


Class Postcontroller extends ccontroller{public    function actions ()    {        return Array (            ' service ' = Array (                ' class ' = ' cwebserviceaction ',                ' Classmap ' =>array (                    ' post ' = ' post ',  //or simply ' Post '                ),)            ,        );    }    ......}

6. Intercepting remote Method invocation (interception of long-distance methods calls)

By implementing the Iwebserviceprovider interface, sevice provider can intercept remote method calls. In Iwebserviceprovider::beforewebmethod, sevice provider can obtain the name of the current Cwebservice instance and the method through the Cwebservice::methodname request. It can return FALSE if the remote method should not be invoked for some reason (for example: unauthorized access).

The above is the Yii Framework Official Guide Series 47--topic: Web Service Content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.