Showing posts with label Yii. Show all posts
Showing posts with label Yii. 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.

Friday, September 17, 2010

Yii - data grid view with some customization of cell content format

Lets start by creating a simple table

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(128) NOT NULL,
  `activationKey` varchar(128) NOT NULL DEFAULT '',
  `createtime` int(10) NOT NULL DEFAULT '0',
  `lastvisit` int(10) NOT NULL DEFAULT '0',
  `superuser` int(1) NOT NULL DEFAULT '0',
  `status` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  KEY `status` (`status`),
  KEY `superuser` (`superuser`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Configure the database connection as shown in one of the earlier posts.

Generate the corresponding model for the table in your database by executing the following commands
>protected\yiic shell

>> model *

Now, I want to create a data grid view to show the details of the table.

To show a link to the new "users" page(with a data grid) on navigation bar, open the file ..\mytestapp\protected\views\layouts\main.php

and add the following entry, in the "mainmenu" div.


widget('zii.widgets.CMenu',array(
            'items'=>array(
array('label'=>'Home', 'url'=>array('/site/index')),
array('label'=>'Users', 'url'=>array('/site/users')),  //####### new entry
array('label'=>'About', 'url'=>array('/site/page', 'view'=>'about')),
array('label'=>'Contact', 'url'=>array('/site/contact')),
array('label'=>'Login', 'url'=>array('/site/login'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest)
),
)); ?>



The site controller needs information about where to render the new "users" page.
This can be done by adding the following method in the ..\mytestapp\protected\controllers\SiteController.php file

public function actionUsers()
    {
    $dataProvider=new CActiveDataProvider('Users');
    $this->render('users',array('dataProvider'=>$dataProvider,
                ));
    }

As you would notice that these methods should begin with "action" prefix.

Create a new file "users.php" at this location
..\mytestapp\protected\views\site\users.php

The contents of this file would look something like this-


$this->pageTitle=Yii::app()->name . ' - Users';
$this->breadcrumbs=array(
    'Users',
);

?><h1>Users

beginWidget('CActiveForm', array(
    'id'=>'members-form',
    'enableAjaxValidation'=>true,
)); ?>

widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'columns'=>array(
   array(
    'name'=>'id',
    'value'=>'CHtml::encode($data->id)'
   ),
   array(
    'name'=>'username',
    'value'=>'CHtml::encode($data->username)'
   ),
   array(
    'name'=>'createtime',
    'value'=>'CHtml::encode(date(\'Y-m-d\', $data->createtime))'  //this will format the unix timestamp to a custom date format
   ),
   array(
     'name'=>'lastvisit',              
     'value'=>'CHtml::encode(date(\'Y-m-d\', $data->lastvisit))'      // format the cell with date format
   ),
   array(
     'name'=>'status',
     'value'=>'CHtml::encode($data->status==1 ? \'Active\': \'Inactive\' )' 
// to render the gridview cell with a particular value
    ),
    ),
)); ?>
endWidget(); ?>


The page should be hosted at
http://localhost/mytestapp/index.php/site/users
or
http://localhost/mytestapp/index.php/?r=site/users

depending on the url manager setting in the config file.

Thursday, September 9, 2010

Setup and debug an Yii app in Netbeans IDE

After using Eclipse for a while I switched to Netbeans IDE for Yii development. It seems faster and easier to setup. Following is my experience of setting up the development environment.

Create a project stub using the following command -
>> yii-1.1.3.r2247\framework\yiic webapp mytestapp

Open Netbeans IDE and proceed with the following steps -
1. Click on File-> New Project
    This will open up a dialog box. Select "PHP" under "Categories" and under "Projects" select "PHP Applications with Existing Sources".


    Click Next.
2. In the "Sources Folder", input the path of "mytestapp" folder on your machine.
    Assign a project name. "mytestapp" for my case.
    Select a PHP version.
    Click Next
3. The options in this form should be set up automatically like below.
   

    Click Finish
   
    This should set up your Yii project in Netbeans IDE.
   
4. Go to "Debug" menu on the top bar on Netbeans IDE. Select "Debug Project(mytestapp)" and you should be able to debug your project.


5. "Continue(F5)" option in Debug can be used to resume a stopped debug session.
   

Tuesday, August 24, 2010

Yii - Authentication from mysql database using a md5 password

Before proceeding make sure the database has been connected to Yii application. (see previous post)
For this example, the passwords are stored in the database as md5 hash.
You may be required to change the password encoding scheme.

Edit the authenticate method in ../my_app/protected/components/UserIdentity.php to look like this -

public function authenticate()
    {
        //$users=array(
            // username => password
            //'demo'=>'demo',
            //'admin'=>'admin',
        //);
       
        $user = myUsersTable::model()->findByAttributes( array( 'my_userid_column_name' => $this->username));
        if ($user===null) { // No user was found!
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        }
        // $user->Password refers to the "password" column name from the database
        else if($user->Password !== md5("my_salt1".$this->password))
        {   
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        }
        else { // User/pass match
            $this->errorCode=self::ERROR_NONE;
        }       
        return !$this->errorCode;
    }

Enter the username/password pair on the login page and you should be good to go.

Sunday, June 20, 2010

Yii + MySql + Wamp







First, I installed WampServer, which is a package of Apache, Php and MySql coupled into one. In the httpd.conf file I pointed the “DocumentRoot” and “Directory” configurations to the directory, where I would have my application and Yii framework.


I copied the Yii framwork in "d:/workspace/app_demo/”

To create the stub application from yii, I executed these commands for my setup:

>cd D:\workspace\app_demo

>yii\framework\yiic webapp myapp

-------

This created an application “myapp” under “app_demo” folder.

The “/app_demo/myapp/protected/config/main.php” file contains the database configurations. By default the database was pointed to an sqlite database. I changed that, to point to Mysql database. So I had these settings for my mysql database.

/* 'db'=>array(

'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',

),*/

'db'=>array(

'connectionString' => 'mysql:host=localhost;dbname=pages_db',

'emulatePrepare' => true,

'username' => 'root',

'password' => '',

'charset' => 'utf8',

),

I also enabled logging through this file to look like this:

'log'=>array(

'class'=>'CLogRouter',

'routes'=>array( array('class'=>'CFileLogRoute',

'levels'=>'error, warning',

),

array('class'=>'CWebLogRoute',

), ), ),

-------

My database had two tables (user and address). The sql is shown below:

CREATE TABLE IF NOT EXISTS `address` (

`addressid` int(11) NOT NULL AUTO_INCREMENT,

`firstline` varchar(45) DEFAULT NULL,

`secondline` varchar(45) DEFAULT NULL,

`city` varchar(45) DEFAULT NULL,

`state` varchar(45) DEFAULT NULL,

`country` varchar(45) DEFAULT NULL,

PRIMARY KEY (`addressid`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `user` (

`userid` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'This contains the userid of the user',

`fname` varchar(128) NOT NULL COMMENT 'This contains the first name of the user',

`lname` varchar(128) DEFAULT NULL COMMENT 'This contains the last name of the user',

`sex` varchar(1) NOT NULL COMMENT 'This contains the sex of the user',

`age` int(100) DEFAULT NULL COMMENT 'This contains the age of the user',

`creation_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'This contains the user account creation',

`user_addressid` int(11) DEFAULT NULL,

PRIMARY KEY (`userid`),

KEY `fk_user_address` (`user_addressid`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `user` ADD CONSTRAINT `fk_user_address` FOREIGN KEY

(`user_addressid`) REFERENCES `address` (`addressid`) ON DELETE NO ACTION ON

UPDATE NO ACTION;

-------

I had to create corresponding models for the tables. After the database configuration, I ran the following commands to create the models in my app.

cd app_demo\myapp

D:\workspace\app_demo\myapp>protected\yiic shell index.php

This opened the Yii Interactive Tool.

Yii Interactive Tool v1.1 (based on Yii v1.1.2)

Please type 'help' for help. Type 'exit' to quit.

>> model *

The following model classes (tables) match your criteria:

1. Address (address)

2. User (user)

Do you want to generate the above classes? [Yes|No] yes

generate models/Address.php

generate fixtures/address.php

generate unit/AddressTest.php

generate models/User.php

generate fixtures/user.php

generate unit/UserTest.php

The following model classes are successfully generated:

Address, User

If you have a 'db' database connection, you can test these models now with:

$model=User::model()->find();

print_r($model);

-------

After this, I edited the actionIndex function in SiteController.php to look like this:

public function actionIndex()

{

// renders the view file 'protected/views/site/index.php'

// using the default layout 'protected/views/layouts/main.php'

$this->render('index', array(

'user' => User::model()->findAll()

));

}

In the index.php, I added the following table to display the records from the database:

 
foreach($user AS $us):?> 
 echo $us->fname;?> 
echo $us->lname;?> 
echo $us->age;?> 
echo $us->user_address->city;?> 
 endforeach;?>

Then I pointed my browser to http://localhost/myapp/index.php and this generated a table with the results.

More on this later...