Friday, February 4, 2011

Yii web service and php soap client

A web service is a method of communication between two machines. The web methods are exposed for world wide access. Yii has support for implementing web services. It uses SOAP as its foundation layer.

To create a web service-

1. Create a web app using Yii console application.
2. Inside the controllers folder, create a file lets say 'ServiceController.php'.
3. Add the following code, which implements two functions. One adds a session variable and the other returns it back.
<?php
class ServiceController extends CController
{
   public function actions()
    {
       return array(
        'wreader' => array(
          'class' => 'CWebServiceAction',
        ),
      );
    }

    /**
     * @param string username
     * @return float
     * @soap
     */
     public function getauth($uname)
     {
              
            $session = Yii::app()->session;
            $session['u_id'] = 1111;
            return 1;
     }

     /**
     * @param string username
     * @return float
     * @soap
     */
     public function getemp($uname)
     {
        $session = Yii::app()->session;
        return isset($session['u_id'])?$session['u_id']:999;
     }
}

* Remember to mark the web methods with the tag @soap in its doc comment. Yii relies on doc comment to specify the data type of the web method's input parameters and return value.

Create a php file and enter the following code which consumes the web service.
<?php
$client=new SoapClient('http://127.0.0.1/s/index.php/service/wreader');
echo "\n".$client->getauth('harpreet');
echo "\n".$client->getemp('harpreet');

?>

Execute the php script in a terminal to check out your web service.

Open to suggests/improvements.

10 comments:

Anonymous said...

I seldom leave comments on blog, but I have been to this post which was recommended by my friend, lots of valuable details, thanks again.

Dharma said...

Nice Post..saved my last night.. Thanks

sallu said...

wreader method is not found so how to wtite it

sallu said...

I got it... thanks

Anonymous said...

Thanks a lot i have been searching for this very nice tutorial.
Looking more...

Guruprabakaran

Shahid Karimi said...

Great tips. Thanks freind

Shahid Karimi said...

Great tips. Thanks freind

Shahid Karimi said...

Great tips. Thanks freind

Anonymous said...

Hello
This article is very useful for me..
But can you please tell me where to create client.php file

Anonymous said...

Good post.
I have a question, how to thrown exceptions?