Showing posts with label soap. Show all posts
Showing posts with label soap. Show all posts

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.