PHP Trait a new feature

PHP5.4 introduced a new feature named trait. Trait can improve code reusability and remove the limitation of the lack ofmultiple inheritance in PHP. We can use trait to gain the benefits of multiple inheritance Here are some basic concepts of traits.

I am declaring our first trait here.

trait our_trait1
{
public function foo() { echo ‘I am in trait function foo’; }
public function bar() { echo ‘I am in trait function bar’; }
}

Next we create a class

class our_class1
{
use our_trait1; //using our trait
}

$class_obj = new our_class1();
$class_obj->foo(); // will print I am in trait function foo
$class_obj->bar(); // will print I am in trait function bar

In the above example we use single inheritance.

Next is multiple inheritance

trait our_trait1
{
public function foo() { echo ‘I am in our_trait1 function foo’; }
}

trait our_trait2
{
public function bar() { echo ‘I am in our_trait1 function bar’; }
}

Next we create a class

class our_class1
{
use our_trait1,our_trait2; //using our trait
}

$class_obj = new our_class1();
$class_obj->foo(); // will print I am in our_trait1 function foo
$class_obj->bar(); // will print I am in our_trait2 function bar

This is a simple introduction to traits.

More details can be found in
http://in2.php.net/traits

Phpmyadmin and FOUND_ROWS() in Mysql

Today I was testing a Mysql query using phpmyadmin. The query is like this
SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name LIMIT 0, 5
after runing this query I tried to get the total rows using

SELECT FOUND_ROWS() as row_count;
But the query showed wrong results. After a lot of googling I found that the issue is with phpmyadmin.

When I tried the same query using Mysql terminal the results are fine.

I think phpmyadmin is executing some other queries after running our query. I think this will be usefult to someone having the same issue :) .

Symfony install plugin manually

Last day I had one situation where I need to install a symfony plugin maually. I am writing down the steps below so that some one may find this useful.

Installation

1. Download the plugin from the symfony site.
2. unzip the file and if the folder has version number , remove that.
3. Copy the plugin to the projectpath/plugins
4. Edit config/ProjectConfiguration.class.php to add
$this->enablePlugins(‘pluginName’);
5. Run symfony plugin:publish-assets in the command line.

Uninstallation.

1. Edit config/ProjectConfiguration.class.php and remove the entry corresponding to the plugin.
2. Run symfony plugin:publish-assets in the command line.

Upload an image to a facebook album Facebook PHP SDK

Simple function to upload an image to a facebook album.
The function will check if the album name exists or not. If the name exists it will add that image to that album otherwise it will create a new one.

First download PHP SDK from
http://developers.facebook.com/docs/reference/php/
then include facebook.php file before calling this function.

function upload_to_facebook($image_data, $access_token)
{
$facebook = new Facebook(array(
‘appId’ => FB_APP_ID,
‘secret’ => FB_SECRET_KEY,
));

$facebook->setFileUploadSupport(true);
$albums = $facebook->api(‘/me/albums’, ‘get’, array(‘access_token’ => $access_token));
foreach ($albums[data] as $album)
{
if ($album['name'] == $image_data['album_name'])
{
$album_id = $album['id'];
}
}

if (!$album_id)
{
//Create an album
$album_details = array(
‘message’ => ‘Album by FB APP’,
‘access_token’ => $access_token,
‘name’ => $image_data['album_name']
);
$create_album = $facebook->api(‘/me/albums’, ‘post’, $album_details);
//Get album ID of the album you’ve just created
$album_id = $create_album['id'];
}

//Upload a photo to album of ID…
$photo_details = array(
‘message’ => ‘test image’,
‘access_token’ => $access_token,
);

$photo_details['image'] = ‘@’.realpath($image_data['file']);

$upload_photo = $facebook->api(‘/’.$album_id.’/photos’, ‘post’, $photo_details);

return $upload_photo;
}

Symfony Password Validation – check for strong password

In my current project I am using the following code in symfony to validate password field to check if the password is strong.

The code checks if the password contains atleast one uppercase, one lower case and one digit

$this->validatorSchema['password'] = new sfValidatorRegex(array(‘pattern’ => ‘/^.*(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[d]).*$/’,'required’ => true)

Someone may find this useful :)

Get Total Record Count in Mysql Select Query with Limit

I found one solution in MYSQL for getting the total record count in a select query with limit. This may be some times useful for displaying the record count while paginating. Normally we use one query to get the total records and then another select query with limit to get the records to display in the page.

SELECT COUNT(*) FROM blog_posts WHERE title LIKE ‘php%’;

SELECT title, content FROM blog_posts WHERE title LIKE ‘php%’ LIMIT 1,10;

These 2 queries can increase our page load time. In this case we can use SQL_CALC_FOUND_ROWS option in our query. For this we can modify our query as shown below.

SELECT SQL_CALC_FOUND_ROWS title, content FROM blog_posts WHERE title LIKE ‘php%’ LIMIT 1,10;
SELECT FOUND_ROWS(); -> this query will output the total record count.

The second query should be run immediately after the first one. Although this solution also requires two queries it’s much more faster, as you execute the main query only once.

This indeed helped me in my current project. The table type was innodb in my case.

CSV parsing using SPL class PHP (SplFileObject)

I tested the SPL class for parsing csv files.SplFileObject class has lot of features and one among them is CSV parsing.


The following is a sample code.

My csv file  (student.csv)


Student name, class,age
Student A,class 1,4
Student B,Class 10,15
Student C,Class 4,8


PHP CODE


<?php
$file = new SplFileObject(“student.csv”);
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY |SplFileObject::DROP_NEW_LINE); //This line removes empty array if there is an empty line .
foreach ($file as $row) {
list($name, $class, $age) = $row;
printf(“A %s is in %s and the age is %d  yearsn”, $name, $class, $age);
}
?>


OUTPUT


Student A is in class 1 and the age is 4 years
Student B is in Class 10 and the age is 15 years
Student C is in Class 4 and the age is 8 years
The above class can be used instead of the old fgetcsv() function.

 

Standard PHP Library New Array Feature (SplFixedArray)

Most of you might have heard about SPL in php 5.x. SPL is a set of interfaces classes and objects that solve common development challenges.

I found a new SPL feature in php 5.3. That is SplFixedArray. It has some major difference from PHP traditional arrays.

Traditional PHP arrays are allocated dynamically. In case of SplFixedArray the array size has to be defined while creating the array. Also it allows only integer indexes. PHP array functions will not work with SplFixedArrays.

eg:
$arr = array(1, 2, 3, 4);
$arr[10] = 45;
This is perfectly acceptable in case of traditional array. But in SplFixedArray the array size has to be defined while creating the array.
eg:
$arr = new SplFixedArray(5);
Here memory is allocated while we are creating the array. In native PHP arrays the memory allocation is done dynamically. Hence it is slower.

The following are some advantages of SplFixedArray
Faster write time
Less memory usage

If you are in an environment where you will need a few arrays with predetermined sizes, the SplFixedArray is the best choice. However, if you will be creating numerous arrays, or the size is unknown, then it is better to use the native PHP array.

Conditional Statements in Mysql IF and CASE

In some situations we need to use some conditional statements in mysql query. In such situation there are two MYSQL statements which comes handy. They are CASE and IF.

CASE is similar to the Switch statement in php/c.

Usage is as below:

CASE

SELECT name, Case gender
WHEN ‘male’ THEN ‘I am a man’
WHEN ‘female’ THEN ‘I am a woman’
ELSE ‘Gender unknown’
as message

IF

SELECT IF(value >= 100, Century, value) AS score
FROM score_card

It has 3 parameters
1. condition (value >= 100)
2. if condition is true second parameter is returned (Century is assigned to score).
3. If condition is false 3 rd parameter is returned ( value is assigned to score).