Interfaces and Abstract Class

Use abstraction if you have default methods (with accompanying code) for inheritors. Use interfaces if you just need to make sure that classes inheriting from this parent should implement all methods defined.

I use abstract classes when I want the inheriting classes to inherit some functionality, and interfaces when I want to set some minimum structural criteria for a group of classes.

One thing to remember is that any given class can “inherit” (technically implement) many interfaces but only one sub-class (be that abstract or not).

Interface is a contract whereas Abstract Class is actually a class. Objects cannot be instantiated in either Interface or Abstract Classes.

PHP interfaces can have constants, but not properties (instance variables). If you don’t need to modify your “property”, you can use a constant instead.

For interfaces also talk about “extending” interfaces and “multiple interface inheritance”

Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method’s signature – they cannot define the implementation.

– Abstract classes can have consts, members, method stubs and defined methods, whereas interfaces can only have consts and methods stubs.
– Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public.
– When inheriting an abstract class, the child class must define the abstract methods, whereas an interface can extend another interface and methods don’t have to be defined.
– A child class can only extend a single abstract (or any other) class, whereas an interface can extend or a class can implement multiple other interfaces. Abstract class can extend another abstract class though.
– A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility.

Abstract Class vs Interface in PHP

Abstract Class

abstract class Animal { 
  function greeting() { 
    $sound = $this->sound();      // exists in child class by contract 
    return strtoupper($sound); 
  } 
  abstract function sound();      // this is the contract 
} 
class Dog extends Animal { 
  function sound() {              // concrete implementation is mandatory 
    return "Woof!"; 
  } 
}

Interface

interface animal {
function breath();
function eat();
}
Note: the interface’s functions/methods cannot have the details/guts filled in – that is left to the class that uses the interface.
Example of a class using an interface:
class dog implements animal{
function bark() {
echo “yap, yap, yap …”;
}
/* the interface methods/functions must be implemented (given their ‘guts’) in the class */
function breath() { echo “dog is breathing …”;}
function eat() { echo “dog is easting …”;}
}

Finding if a string occurs in another string

Options:
1) strpos
2) strstr

If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead of strstr.

For case insensitive queries, use stripos and stristr

strstr: Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack. Has option in new version of PHP to return part of string before needle also. Returns false if not found.

strpos: Find the numeric position of the first occurrence of needle in the haystack string.
Returns false if not found.

Different types of errors in PHP

There are three basic types of runtime errors in PHP:

1. Notices: These are small, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although the default behavior can be changed.

2. Warnings: Warnings are more severe errors like attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.

3. Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place.

Can be changed by
a) php statement error_reporting — Sets which PHP errors are reported
b) php.ini : error_reporting = E_ALL

Yii Built In functions – Generic

// For dropdown list
$list=CHtml::listData(SysState::model()->findAll(), 'state_id', 'state_name');
echo $form->dropDownList($model,'state_id', $list, array('empty'=>'Select state'));

// dynamic dropdown populate
Below lines create the country dropdown which updates state dropdown
'POST', //request type
'url' => Yii::app()->createUrl('manager/events/dynamicStates/'), //url to call.
//Style: ii::app()->createUrl('currentController/methodToCall')
'update' => '#Events_state_id', //selector to update
'data'=> array('country_code'=>'js:this.value')
//leave out the data key to pass all form values through
)
?>
dropDownList($model,'country_code', $list['countries'], array('empty'=>'--none--', 'class'=>'form-control', 'ajax'=>$ajaxStatePopulate)) ?>
error( $model, 'country_code'); ?>

The above code updates the below line
dropDownList($model,'state_id', $list['states'], array('empty'=>'--none--', 'class'=>'form-control')) ?>
error( $model, 'state_id'); ?>

Called url will have the below code
$result = States::model->findAll();
$data = CHtml::listData($result,'id','name');
//return CHtml::listData($result, 'code', 'name');print_r($data);
echo CHtml::tag('option',
array('value'=>''),CHtml::encode('--none--'),true);
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}

// NEXT
// To update the of the value in text field
pre_reg_start_date = Common::formatDbDate($model->pre_reg_start_date)?>
textField( $model, 'pre_reg_start_date', array('class'=>'form-control selectDate')); ?>

// NEXT : update label
labelEx( $model, 'pre_reg_start_time', array('label'=>'Time') ); ?>

// NEXT : create link with id
$event_id))?>" class="btn btn-primary">Link

// NEXT : Set your messages in a controller:
Yii::app()->user->setFlash('success', "Data1 saved!");
Yii::app()->user->setFlash('error', "Data2 failed!");
Yii::app()->user->setFlash('notice', "Data3 ignored.");

Display them in your view:
user->getFlashes() as $key => $message) {
echo '

' . $message . "

\n";
}
?>

// NEXT : Create url examples
$url=$this->createUrl($route,$params); // syntax

$url = Yii::app()->createUrl('site/index');
index.php?r=site/index

$url = Yii::app()->createUrl('site/index', array('id'=>100));
index.php?r=site/index&id=100

Create URL from Controller
Yii::app()->controller->createUrl("index", array("id"=>100));
index.php?r=site/index&id=100

create url withing same controller with id as parameter
$this->createUrl('index',array('id'=>100));

Create absolute URL:
In order to create an absolute path url you need to use createAbsoluteUrl() function:
Yii::app()->createAbsoluteUrl('site/index',array('id'=>100));
http://yourdomain.com/index.php?r=site/index&id=100

echo CHtml::link('text', array('site/index', 'id'=>100));
text

Redirection example
$this->redirect(array('site/index','id'=>100));
index.php?r=site/index&id=100

$this->redirect(array('site/index','id'=>100));

// Get base url
Yii::app()->baseUrl

// get current url before ? mark
Yii::app()->request->pathInfo

// Theme url
Yii::app()->theme->baseUrl

// get the theme name
Yii::app()->theme->name

// get base path
$this->getBasePath()

// home page url
$this->getHomeUrl()

// url related properties
Yii::app()->request->pathInfo
Yii::app()->request->url
Yii::app()->request->requestUri
Yii::app()->request->queryString
Yii::app()->request->isSecureConnection
Yii::app()->request->isPostRequest
Yii::app()->request->isAjaxRequest
Yii::app()->request->serverName
Yii::app()->request->urlReferrer
Yii::app()->request->userHostAddress // IP address

// NEXT : rules example to validate the date and time
array('wave_date', 'type', 'type'=>'date', 'dateFormat'=>'MM/dd/yyyy'),
array('wave_time', 'type', 'type'=>'time', 'timeFormat'=>'hh:mm a'),

Text field

Example:
'form-control')); ?>

Text field using Form. It does same as above
textField( $model, 'name', array('class'=>'form-control')); ?>

Text field without form and model

Creating a simple widget
Step 1: components/BreadCrumb.php:
render('breadCrumb');
}

}
?>
Step 2: components/views/breadCrumb.php

Step 3: Call from your actuall view as below
widget('application.components.BreadCrumb', array(
'crumbs' => array(
array('name' => 'Home', 'url' => array('site/index')),
array('name' => 'Login'),
),
'delimiter' => ' → ', // if you want to change it
)); ?>

// NEXT : Logging
Yii::log($message, $level, $category);
Yii::trace($message, $category);

// NEXT : end application
Yii::app()->end(); // does

// Set get session value
Yii::app()->session["lang"] = "English";
echo Yii::app()->session["lang"]

Yii DB built in functions – Reference

Quick reference – Yii inbuilt functions – DB related
—————————————————-

###### Active Record functions: ############
Different ways to query
// 1st way
$criteria=new CDbCriteria;
$criteria->select=’title’; // only select the ‘title’ column
$criteria->condition=’postID=:postID’;
$criteria->params=array(‘:postID’=>10);
$post=Post::model()->find($criteria);

// 2nd way
$post=Post::model()->find(array(
‘select’=>’title’,
‘condition’=>’postID=:postID’,
‘params’=>array(‘:postID’=>10),
));

//Other ways
// Find All
// find all rows satisfying the specified condition
$posts=Post::model()->findAll($condition,$params);
// find all rows with the specified primary keys
$posts=Post::model()->findAllByPk($postIDs,$condition,$params);
// find all rows with the specified attribute values
$posts=Post::model()->findAllByAttributes($attributes,$condition,$params);
// find all rows using the specified SQL statement
$posts=Post::model()->findAllBySql($sql,$params);

User::model()->findAll(‘first_name=? AND last_name=?’, array(‘Paul’, ‘Smith’));
User::model()->findAllByAttributes(array(‘first_name’=>’Paul’, ‘last_name’=>’Smith’));

// find one
$post=Post::model()->find($condition,$params);
$post=Post::model()->find(‘postID=:postID’, array(‘:postID’=>10));

// find by primary key
$post=Post::model()->findByPk($postID,$condition,$params);

// find by attributes
$post=Post::model()->findByAttributes($attributes,$condition,$params);
$post=Post::model()->findByAttributes();

// find by specified SQL statement
$post=Post::model()->findBySql($sql,$params);

// count
$n=Post::model()->count($condition,$params);

// CREATE : creating record
$post=new Post;
$post->title=’sample post’;
$post->content=’content for the sample post’;
$post->create_time=time(); // $post->create_time=new CDbExpression(‘NOW()’);
$post->save();

// UPDATE: Updating Record
$post=Post::model()->findByPk(10);
$post->title=’new post title’;
$post->save(); // save the change to database

// DELETE: Delete record
$post=Post::model()->findByPk(10); // assuming there is a post whose ID is 10
$post->delete();

// Scopes
how to make use of scopes
In your model make a entry as below
// scope to get the 5 records of status=1 and recently updated
public function scopes()
{
return array(
‘published’=>array(
‘condition’=>’status=1’,
),
‘recently’=>array(
‘order’=>’create_time DESC’,
‘limit’=>5,
),
);
}

And then use the below statement to query.
$posts=Post::model()->published()->recently()->findAll();

// write in model class to to some ops before saving
public function beforeSave() {
if ($this->isNewRecord)
$this->created = new CDbExpression(‘NOW()’);
else
$this->modified = new CDbExpression(‘NOW()’);
// anything else.. like, date modification, time modification, etc..

return parent::beforeSave();
}

######## Query builder functions: ############
// NEXT : sql command writing
$command = Yii::app()->db->createCommand(‘SELECT * FROM tbl_user’);

// fetch row
$user = Yii::app()->db->createCommand()
->select(‘id, username, profile’) // to fetch all use ->select(‘*’)
->from(‘tbl_user’) // for multiple table use as ->from(array(‘tbl_user’, ‘tbl_profile’))
->where(‘id=:id’, array(‘:id’=>$id))
->queryRow();
OR
$row = Yii::app()->db->createCommand(array(
‘select’ => array(‘id’, ‘username’),
‘from’ => ‘tbl_user’,
‘where’ => ‘id=:id’,
‘params’ => array(‘:id’=>1),
))->queryRow();

// Fetch row using join
$user = Yii::app()->db->createCommand()
->select(‘id, username, profile’)
->from(‘tbl_user u’)
->join(‘tbl_profile p’, ‘u.id=p.user_id’) // join, leftJoin, rightJoin, crossJoin, naturalJoin
->where(‘id=:id’, array(‘:id’=>$id))
->queryRow();

// fetch all
$user = Yii::app()->db->createCommand()
->select(‘id, username, profile’)
->from(‘tbl_user’)
->where(‘id=:id’, array(‘:id’=>$id))
->limit(10, 20) // limit 10 and offset 20
->queryAll();

$users = Yii::app()->db->createCommand()
->select(‘*’)
->from(‘tbl_user’)
->queryAll();

// display SQL statement
$sql = Yii::app()->db->createCommand()
->select(‘*’)
->from(‘tbl_user’)
->text;

// INSERT
// build and execute the following SQL:
// INSERT INTO `tbl_user` (`name`, `email`) VALUES (:name, :email)
$command->insert(‘tbl_user’, array(
‘name’=>’Tester’,
’email’=>’tester@example.com’,
));

// UPDATE `tbl_user` SET `name`=:name WHERE id=:id
$command->update(‘tbl_user’, array(
‘name’=>’Tester’,
), ‘id=:id’, array(‘:id’=>1));

// DELETE FROM `tbl_user` WHERE id=:id
$command->delete(‘tbl_user’, ‘id=:id’, array(‘:id’=>1));

// NEXT
// create a new entry with time modification example
$post=new Post;
$post->title = “Some title”;
$post->desciption = “Some description”;
$post->create_time=new CDbExpression(‘NOW()’);
// $post->create_time=’NOW()’; will not work because
// ‘NOW()’ will be treated as a string
$post->save();

isset vs empty vs array_key_exists vs is_null

isset — Determine if a variable is set and is not NULL

empty — Determine whether a variable is empty. it will return true if the variable is an empty string, false, array(), NULL, “0″, 0, and an unset variable. (equivalent to !$var without the notice). empty() comes with quite a few caveats, since it considers the integer 0 and the string “0” to be empty (among other things).

is_null — Finds whether a variable is NULL
is_null() is opposite of isset(), except for one difference that isset() can be applied to unknown variables, but is_null() only to declared variables

array_key_exists vs isset

isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.