Sunday, March 9, 2014

Yii-call-function-from-other-class

In this tutorial i will show how to call a method from a class

first we should import the class.

after that we should instantiate the imported class.

then we can call method via instance.

Example,


class AnotherController extends Controller
{

public function __construct($id=NULL)
{

}

public function message()
{
return 'Message from Another Controller';
}
}

?>

Above lines shows a class(Controller). assume that this class is placed in side

the contollers folder.

we want to access method "message" from another controller.

solutioin is ,

public function messageFromAnotherClass()
      {
     
  Yii::import("application.controllers.AnotherController");
  $another = new AnotherController();  
  return $message = $another->message();
      }

yii-create-cutom-application-component


In this tutoial , i will show you how to create a simple custom Application Component.

First of all create a file named simple with following codes and put the file in the path

protected/components/Simple.php


class Simple  extends CApplicationComponent
{

    public function init()
    {
echo 'Simple Initiated
';
    }

    public function message()
    {
      return 'Message from Simple';
    }
   
   
}


?>

do the following changes int the main.php under config folder

'components'=>array(
........
            'simple'=>array('class'=>'Simple'),
.........

),


Now its time to call method in the created component.

steps are,

echo Yii::app()->simple->message();


output is

Simple Initiated
Message from Simple

Thursday, March 6, 2014

Yii-cgridview-table-css-class

By default Yii Cgridview have a spcific CSS formatting in gridview's table.

But we can apply css table class whatever we want to display.

we can apply it by htmlOptions array.

Example,

<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'account-grid',
'dataProvider'=>$model->search(),
 'htmlOptions' => array('class' => 'table table-hover table-striped table-bordered table-condensed'),
'filter'=>$model,
'columns'=>array(
'id',
'account_name',
array(
'class'=>'CButtonColumn',
),
),
)); ?>

yii-model-limited-rows

Yii model fetch limited rows Example

Assume that we have a model with two columns, they are id and account_name

$datas = Account::model()->findAll();

echo CJSON::encode($datas);

[{"id":"1","account_name":"Tea"},{"id":"2","account_name":"Food"},{"id":"3","account_name":"Travel"},{"id":"4","account_name":"Pettycash"}]

The above line shows the values in  the model.

we want to display only limited rows.

Lines are a follows,

$criteria = new CDbCriteria;
$criteria->limit = "3";
$datas = Account::model()->findAll($criteria);

echo CJSON::encode($datas);

ouput is

[{"id":"1","account_name":"New Tea"},{"id":"2","account_name":"Food"},{"id":"3","account_name":"Travel"}]

Yii-fetch-rows-order-by

Yii model order by column example.

Assume that we have a model with two columns, they are id and account_name

$datas = Account::model()->findAll();

echo CJSON::encode($datas);

[{"id":"1","account_name":"Tea"},{"id":"2","account_name":"Food"},{"id":"3","account_name":"Travel"},{"id":"4","account_name":"Pettycash"}]

The above line shows the values in the model.

we want show values that are ascending order by account_name column;

Lines are as follows,

$criteria = new CDbCriteria;
$criteria->order = "account_name asc";
$datas = Account::model()->findAll($criteria);

echo CJSON::encode($datas);

// output is

[{"id":"2","account_name":"Food"},{"id":"1","account_name":"New Tea"},{"id":"4","account_name":"Pettycash"},{"id":"3","account_name":"Travel"}]

Yii-update-model-by-primary-key

Yii model Update Row By primary Key Example

Assume that we have a model with two columns, they are id and account_name

$datas = Account::model()->findAll();

echo CJSON::encode($datas);

[{"id":"1","account_name":"Tea"},{"id":"2","account_name":"Food"},{"id":"3","account_name":"Travel"},{"id":"4","account_name":"Pettycash"}]

The above line shows the values in the model.

we want to update  account_name by Primary key.

line are as follows,

$pk=1;

$single = Account::model()->findByPk($pk);

$single->account_name = "New Tea";  // actual value is Tea

$single->save();

after These lines we got following value. while checking.....

$single = Account::model()->findByPk($pk);

echo $single->account_name;

// output is New Tea

Yii-count-model-rows-by-attribute

Yii Count Records by attribute Example

Assume that we have a model with two columns, they are id and account_name

$datas = Account::model()->findAll();

echo CJSON::encode($datas);

[{"id":"1","account_name":"New Tea"},{"id":"3","account_name":"Travel"},{"id":"4","account_name":"Pettycash"},{"id":"13","account_name":"Travel"}]

The above line shows the values in the model.

we want to count rows by  specific acount_name.

line are as follows,


$data = Account::model()->findAllByAttributes(array(
                  'account_name'=> 'Travel',
               ));

echo count($data);

//output is 2

yii-model-fetch-row-by-primary-key

Yii model fetch Row By primary Key Example

Assume that we have a model with two columns, they are id and account_name

we need to fecth a particular row based on primary key value.

$datas = Account::model()->findAll();

echo CJSON::encode($datas);

[{"id":"1","account_name":"New Tea"},{"id":"2","account_name":"Food"},{"id":"3","account_name":"Travel"},{"id":"4","account_name":"Pettycash"}]

The above line shows the values in the model.

we want to get acount_name that have a primary key value is 1.

lines are,


$pk=1;
$single = Account::model()->findByPk($pk);
echo $single->account_name;


// output is New Tea

Friday, February 21, 2014

PHP oops Method overriding Example



class Processes
{
	public function process1()
	{
		echo  'I am process 1';
	}

      public function process2()
	{
		echo  'I am process 2';
	}

	public function process3()
	{
		echo  'I am process 3';
	}

      public function startProcess()
	{
		$this->process1();
		$this->process2();
		$this->process3();
	}

}


class ChildProcess extends Processes
{

	public function process2()
	{
		echo  'I am overrided process 2';
	}


}

$process = new Processes();

$process->startProcess();

/* output is

I am process 1
I am process 2
I am process 3

*/


$child = new ChildProcess();
$child->startProcess();

/*
output is 

I am process 1
I am overrided process 2
I am process 3

*/

From the above example,

Processes is a parent class having 4 methods.  method startProcess() display other three methods content.

if we want to override any of the methods we should create a child class and extend which method we want to override.

in the example process2 overrided by child class.

when this line executes $child->startProcess(); , compiler first execute process1 from parent and execute overrided method

pocess2 then control goes to process3.

PHP oops Hybrid Inheritance Example



class GrandFather
{
	public function pocketMoney()
	{
		return  'Take this 1000 $';
	}

}


class Father extends GrandFather
{
	public function myIncome()
	{
		echo "My father told ".parent::pocketMoney();
	}
	
	public function myExpense()
	{
		return 'Take this 500 $
'; } } class Elder extends Father { public function myEarning() { echo "Father told me ".parent::myExpense(); } } class Younger extends Father { public function myEarning() { echo "Father told me ".parent::myExpense(); } } $elder = new Elder(); $elder->myEarning(); // output Father told me Take this 500 $ $younger = new Younger(); $younger->myEarning(); // output Father told me Take this 500 $

PHP oops Hierarchical Inheritance Example




class Father
{
	public function pocketMoney()
	{
		return  'Take this 500 $';
	}

}

class Elder extends Father
{
		
	public function myEarning()
	{
		echo "Father told me ".parent::pocketMoney();

	}

}

class Younger extends Father
{
	public function myEarning()
	{
		echo "Father told me ".parent::pocketMoney();

	}

	
}


$elder = new Elder();

$elder->myEarning();  // output Father told me Take this 500 $

$younger = new Younger();

$younger->myEarning();  // output Father told me Take this 500 $


PHP oops Multilevel Inheritance Example





class GrandFather
{
	public function gfAge()
	{
		return  ' age is 80';
	}

}

class Father extends GrandFather
{
		
	public function fAge()
	{
		return  ' age is 50';
	}

}

class Son extends Father
{
	public function sAge()
	{
		return  'age is 20';
	}

     public function myHistory()
     {
	 echo "my grand father ".parent::gfAge();
	 echo "my father ".parent::fAge();
       echo "my ".$this->sAge();
     }
	
}


$son = new Son();

$son->myHistory();

// output is

//my grand father age is 80
//my father age is 50
//my age is 20

Above code shows simple example for multi level inheritance,

class GrandFather is a base class , extended by Father class and this is extended by

Son class

myHistory function in Son class access Father class and GrandFather class functions

here the class hieararchy is,


GrandFather
    |
    | 
  Father
    |
    |
   Son 

 

PHP Call parent class function inside child class function example




class Person
{
	
	public function whoAmi()
	{
		return 'I am a person';
	}
	
}

class SimplePerson extends Person
{
	
	public function personEnquiry()
	{
		$whoami = parent::whoAmi();
		echo "The person told ".$whoami;
	}
	
}



$person = new SimplePerson();

$person->personEnquiry();

// output is The person told I am a person

In the above example class Person have a function named whoAmi().

we want to call it inside another class that extends person class.

by using parent:: keyword we can access function from its parent class

parent::whoAmi(); line access the whoAmi function that is defined in the Parent class.

PHP oops Single inheritance Example



class Processes
{
	
	public function process1()
	{
		echo  'process 1 is completed';
	}

	public function process2()
	{
		echo  'process 2 is completed';
	}

	
}

class ChildProcess extends Processes
{
	
	public function process3()
	{
		echo  'process 3 is completed';
	}
	
}



$process = new Processes();

$process->process1(); // output is  process 1 is completed


$process->process2(); // output is process 2 is completed


// access parent class methods

$cprocess = new ChildProcess();

$cprocess->process1(); // output is  process 1 is completed


$cprocess->process2(); // output is process 2 is completed

$cprocess->process3(); // output is process 3 is completed


In the above example we have a class Processes with two methods

the class ChildProcess extends the Processes class.
 
suppose we want to complete a task that should 3 process 

levels then using inheritance,

not necessary to define already defined process1, process2. 

directly we can extend a parent

class and create a child one. Inheritance is very helpful 

to reduce code duplicating. Inheritance is

very simple to use and yet powerfull. 

PHP oops calling a method from another mehod of a class example

class Person
{
	
	public function function1()
	{
		return 'from function1';
	}


      public function function2()
	{
		$function1 = $this->function1();

		echo $function2 = $function1." from function2";
	}
	
}

$person = new Person();

$person->function2();

In the above example class Person have a function named function1.
 we want to call it inside another function named fnction2.
 function1 return a string. by using $this keyword we can access function from a class
 $function1 = $this->function1(); this line access function1 and store the returned
 string "from function1" into $function1 variable;

PHP oops Static function example



class Person
{
	
	public static function statExample()
	{
	   echo 'Hi static  function. no need to instantiate';
	}
	
}



Person::statExample();

Explanation:

Static functions are function that starts with static keyword.

No need to instantiate static functions

Performance methods implemented as static and
instance would little difference in terms of
performance 

The short answer is that static functions are faster.


Yii page size for cgridview pagination



   public function search()
	{
		.............

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
                        'pagination' => array(  'pageSize'=>20),
		));
	}


 Yii cgridviews shows 10 rows per page by default but can change this .

 * model have the search function for cgridview,

 * add the line 'pagination' => array(  'pageSize'=>20), below to the criteria

 * set the pageSize you would like to change.


Yii calling controller from another controller example


   

  public function actionTest()
            {
                Yii::import('application.controllers.SiteController');
                $obj = new SiteController(); 
                $obj->actionSitetest();

            }

 from above example actionTest call a function named Sitetest from  SiteController.

 * first line imports the SiteController.php file,

 * next line instantiate the SiteController class.

 * third line call a function named Sitetest that is defined in the SiteController

Yii - model custom validation eample


   public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('projid, projdate', 'required'),
			array('projid', 'numerical', 'integerOnly'=>true),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, projid, projdate', 'safe', 'on'=>'search'),
                        array('projdate', 'datevalid'),
                        
		);
	}
        
        
        public function datevalid($attribute)
        {
           $projid = $this->projid;
           $projdate    = $this->projdate;
           $conn = Yii::app()->db;
           if($projid!='')
           {
                $cmd  = $conn->createCommand("select startdate from project where id={$projid}");
                $date = $cmd->queryColumn();
                if(strtotime($projdate)<=strtotime($date[0]))
                {
                  echo $this->addError($attribute,"Close Date you are Entered Should not less than or Equal to project start date");
                }
           }
            
            
        }

Yii - fetch rows or row or column from model



  $products = Products::model()->findAll();

  foreach($products as $product)
  {
   echo $product->id;
   ....
   ....
  }
  
  fetch rows by condition example

  $condition = array('condition'=>"id in (1,2,3)");

  $products = Products::model()->findAll($condition);

  the above line fetch product rows that have id 1,2,3.


 fetch single Row

  
 $product = Products::model()->findByPk(1);

 the above line fetch row that have primary key (here id) is 1.

 then

 $product->product_name will display the product_name attribute value.

Yii Cgridview enable disable buttons


               array(
			'class'=>'bootstrap.widgets.TbButtonColumn',
			'template' => '{update}{delete}{view}',
		),


Yii cgridview shows buttons in the above manner,

if you want to disable delete option from the cgridview 

you can easily change as,

                array(
			'class'=>'bootstrap.widgets.TbButtonColumn',
			'template' => '{update}{view}',
		),


Yii - Display DatetimePicker option in form


<?php Yii::import('application.extensions.CJuiDateTimePicker.CJuiDateTimePicker');
                    $this->widget('CJuiDateTimePicker',array(
                        'model'=>$model, //Model object
                        'attribute'=>'date_of_join', //attribute name
                        'mode'=>'datetime', //use "time","date" or "datetime" (default)
                        'language' => '',
                        'options'=>array() // jquery plugin options
                    ));
                ?>
first of all download "CJuiDateTimePicker" extension and extract files
in the protected/extensions/ directory.
after that put above codes in your _form.php file.
if you want to show only date you can change the mode as "date" instead of "datetime".

Yii Dropdown creation in form

                $products = Products::model()->findAll();
		
		$prodlist = CHtml::listData($products,'id', 'name');
		
		
			 
    $form->dropDownList($model, 'product_id',$prodlist, array('prompt'=>'Select Product'));
* from above lines,
* $products is the object that holds all data from Products model;

* $prodlist lists the data "id" is the value and "name" is the text for dropdown

Tuesday, February 18, 2014

PHP Access Modifiers - 3

class Person
{
 public function pub()
 {
  echo 'I am Publicly accessible<br>';
 }

 private function pri()
 {
  echo 'I am Private function<br>';
 }
 protected function pro()
 {
  echo 'I am Protected function<br>';
 }
}



class NewPerson extends Person
{

 public function getPrivatedata()
 {
  parent::pri();
 }

 public function getProtectedata()
 {
  parent::pro();
 }

}



$newperson = new NewPerson;



//$newperson->getPrivatedata();  // Fatal error: Call to private method Person::pri() from context 'NewPerson'



$newperson->getProtectedata();  // Output is I am Protected function




from the above example newperson object trying to access a function , that is defined as private from its class Person. that shows error message. because we cant access it from derived class.

after that we call a function getProtectedata() . it access protected function pro from Person. It can be accessible , because of protected.

so whenever we want to access a function from its child class, it should be defined as protected, else private.

PHP - Access modifiers - 2

class Person
{

 public function pub()
 {
  echo 'I am Publicly accessible<br>';
 }

 private function pri()
 {
  echo 'I am Private function<br>';
 }

 protected function pro()
 {
  echo 'I am Protected function<br>';
 }
}

$person = new Person;



$person->pub();  // output is I am Publicly accessible

$person->pri();  // Fatal error: Call to private method Person::pri()

$person->pro();  // Fatal error: Call to protected method Person::pro()

PHP - Access modifiers - 1


PHP - Access modifiers

 Access modifiers are used to access class members (variables and methods).

Acess modifiers are,

*  Public
*  Private
*  Protect

 Public variable and method can accessible from anywhere .

 Private members only accessible inside the class not the inherited class.

 In other terms private access control is used to maintain encapsulation functionality.

Protected members can only access from derived classes.


class Person
{
 public $name;
 protected $age;
 private $phone;
 
 function setName($name)
 {
  $this->name=$name;
 } 
 
 function getName()
 {
  return $this->name;
 }
 
 function setAge($age)
 {
  $this->age=$age;
 }
 

 function getAge()
 {
  return $this->age;
 }

 function setPhone($phone)
 {
  $this->phone=$phone;
 } 

 function getPhone()
 {
  return $this->phone;
 }


}

$person = new Person;



$person->setName('Sivanthi');
$person->setAge(28);
$person->setPhone('95******53');
echo $person->getName();  // output is  Sivanthi

echo $person->getAge();  // output is  28

echo $person->getPhone();  // output is  95******53

echo "Person Name is ".$person->name;  // output is Person Name is Sivanthi

echo "Person Age is ".$person->age; // Cannot access protected property Person::$age

echo "Person Phone is ".$person->phone; // Cannot access protected property Person::$phone


So we cannot directly access private and protected members from a class,

instead of we can use setters and getters to access those variables.


Monday, February 17, 2014

PHP OOPS Part - 1 - Simple class


PHP one of the Fast growing web programming language. It contains object oriented feature for robust and complex projects design. let us create a simple class in php.
class Product
{
  public $product_id;
  public $product_name;

  public function getProduct()
  {
     echo "Product Name is ".$this->product_name.
  }
  
}

now we need to instantiate the class already created. steps are,
$productobject = new Product;

$productobject->product_name = "Colgate";

$productobject->getProduct();

The output is Product Name is Colgate
Explanation
* class keyword for create class * Product is the name of class
* $product_id and $product_name are class members (public)
* getProduct() is a public access method.
* $productobject = new Product;
new operator is used to instantiate the class
* $productobject->product_name = "Colgate";
the above line assign colgate as product name.
* $productobject->getProduct();
The above line call method getProduct from product class.