Junal on the run

Archive for the ‘CakePHP’ Category

Today, I have received technical reviewer copies of CakePHP Application Development that is written by Anupom Syam and Ahsanur Bari. Both of them are my colleagues and it makes me proud to think that they are Bangladeshi! Another great thing is that i was also a technical reviewer of Hasin Hayder’s Learning Facebook Application Development.

CakePHP Aplication Development

CakePHP Aplication Development

Learning Facebook Application Development

Learning Facebook Application Development

Certainly these tasks were challenging for me, but i’m proud to be a part of these books. I want others to read these books. So i’m going to gift 2 books (one CakePHP copy+ one Facebook copy) to IUB library. Dr.Anwar already welcomed me, soon I will meet him to handover these 2 books.


To check if an image/file URL exist, first thing came in my mind was file_exist() function. Thought it would be the best way to find whether my parameter that is throwing an image url is right or wrong. So I had to set a default image if there was no image found from the given link. file_exist() has a problem that it reads the directory of the file/image so when i’m reading an URL it will always return false. Well, I could separate the directory from the URL but it would be lengthy and messy, so I was searching for a better way. After reading the PHP manual online version I have found that this task can be done by getimagesize(). It returns an Array() with 7 elements. So idea is simple, if I get an array from the given URL then I can say that image is found otherwise not!

An example could be like this:




$default_image =”…/directoryFolder/junal.jpg”;


Recently, I have studied three types of PHP functions and they are: String functions, Date functions and Array functions. I have noted down some functions that were interesting. Well, PHP got thousands of built in functionality and I guess this is what makes PHP great. So, let’s have a look at some interesting functions from my collection.

String functions:

strpbrk ()

–          Search a string for any of a set of characters

Example :

$text = ‘Junal is studying php functions’;

echo strpbrk($text, ‘s’);
What will be the output? Well its will output: “studying php function”, because‘s’ is matched first.


–          This will reverse the given string


echo strrev(“junal likes to be lost”);

output : “tsol eb ot sekil lanuj” – funny eh ?


–          Tokenizing a string

–          Example :

$string = “Junal is being tokenized”;

$tok = strtok($string, ” \n\t”);

while ($tok !== false) {

echo “Word=$tok<br />”;

$tok = strtok(” \n\t”);


Output :



–          Ahh ! This is one of the most interesting and needy one that I used currently one of out facebook application, it uppercase the first letter of first word!


$string = ‘junal rahman’;

echo ucfirst($string);

output : “Junal rahman”

ok this above function make first letter of first word uppercase right. How about if we want all word’s first letter to be uppercase? Simple! We just have to use ucwords() function !

Date Functions:

Well, among all date functions I found one date function interesting 🙂


–          Format a local time/date as integer


$timestamp = strtotime(‘9th February 2008’);

echo idate(‘m’, $timestamp);

Output: “2”

Array Functions


–          Computes the difference of arrays.

–          Example :

$array1 = array(“a” => “junal”, “anupom”, “manzil”, “ahsan”);

$array2 = array(“b” => “junal”, “anupom”, “manzil”);

$result = array_diff($array1, $array2);


output : “ahsan”

array_key_exists ()

–          Checks if the given key or index exists in the array

array_multisort ()

I used this function in several occasions. Very handy function to sort the multiple arrays. It does a lot of help when we want to sort an array by rank/number.


–          Calculate the product of values in an array


$a = array (2, 4, 6, 8);

echo $a;

output :” 384″

natcasesort ()

–           Sort an array using a case insensitive “natural order” algorithm

range ()

–          Create an array containing a range of elements

Well that’s all! After studying these array functions, I have found another interesting thing about ArrayObject.

$array = array(‘1’ => ‘one’,

‘2’ => ‘two’,

‘3’ => ‘three’);

$arrayobject = new ArrayObject($array);

Excellent stuff! By the way, I have to go now. There are thousands thing I don’t know about PHP. Have to get idea about them, have to run ….

Reference : PHP manual.

There are tons of PHP tutorials in the web. But a good tutorial depends on how easily it’s written and of course example is very vital to make a tutorial better. I have just read this tutorial from here, which are actually written for beginners. This tutorial that I’m talking about has three parts. I’m pretty sure if a beginner just read it carefully and practices, it will be really help him/her to understand what PHP and how it actually works. Well, this tutorial will give a good idea about php Framework concept as well.

First part: it starts from the very beginning. It includes database design and describes how to create some basic functions for the application.

Second part: you will see how to create a dynamic menu using php. I did the same thing with CakePHP for my garments ERP project. So, second part will give you some idea about framework concept.

Third part: it says about how to handle multiple items. So you will get a concept of foreach, for and while loop concept.

My requests, if you read these tutorials then please start from the first part. And of course if you run the code in your localhost you will understand it more.

Okay, in my last post I stopped with model. Today, I’m going to start with Controller.

Controller: There is no significant difference between these framework controllers. Cake follows strict naming convention. So that once I follow the naming convention, I don’t have to worry about adding my model in controller. Let me make it clear. In my model when I define my model name like this:

$var name = ‘Post’;

I don’t have to add this Model name to get this table value in my post_controller.php. But if I want to add more models then of course we have to follow this:

var $uses = array(Post’,’AnotherModel’);

Cake controllers feature a number of callbacks you can use to insert logic before or after important controller functions. To utilize this functionality, declare these functions in your controller using the parameters and return values detailed here.

beforeFilter( );  

Called before every controller action. A useful place to check for active sessions and check roles.

afterFilter( );  

Called after every controller action.

beforeRender( );  

Called after controller logic, and just before a view is rendered.

On the other hand CodeIgniter doesn’t have any Callback function like cake. It doesn’t have any model name convention. So every time I have to add or load my model in my controller. Same goes when I add helper.

$this->load->model ('Model_name1', 'Model_name2'...);

$this->Model_name->function ();

I like how cake lets us assign the model name and later we can use it in controller. But we have a solution to do the similar thing in CI.

We can assign the model name in a variable like this:

$this->load->model ('Model_name', 'fubar');

So it makes thing a little easier I guess.

Oh well, as I said earlier cake follows naming convention, so when I have a function in controller called function test(). My view test.ctp will get it automatically. So when I call the controller mysite/controller/test it will automatically get the view. But in CI I have to tell the function which view to load when I call the function. Something like this:


class Blog extends Controller {

function index()


$this->load->view (‘blogview’);




Okay, for time being I’m liking Cake’s aoutomagic features 🙂

Helpers: Uff, CI doesn’t have any AJAX helper!! It has some different and helpful helpers comparing Cake, such as Date Helper, Download Helper, Cookie Helper any many more but man where is AJAX helper??! I prefer cake’s helper because I will get really a good support to use AJAX in my application. Well, I have got an alternative solution to use AJAX helper in CI. Have a look here:


In cake some helpers that are not default, have to be added. On the other hand in CI if we think we will use some helpers almost in all controllers than we can use Auto-loading Helpers.



$autoload[‘helper’] = array(‘url’, ‘file’);

Validation: Again, I should call CI as VC patter framework :). CakePHP handles its validation through the model itself. So I have ” Post” model and let say it has 3 fields called Name, Address and phone. To validate these fields I have to validate them in the model called Post. But in CI there is no restriction. I can do it in Controller. Well, that’s not a major factor. I find it easier but it just makes my controller size bigger [ugly eh?].

An example of Cake’s Validation:

var $validate = array(

‘login’ => ‘/[a-z0-9\_\-]{3,}$/i’,

‘password’ => VALID_NOT_EMPTY,

’email’ => VALID_EMAIL,

‘born’ => VALID_NUMBER


Well it uses variable $validate which is okay. But I prefer to use custom validation to use beforeSave() in my controller. And well, Cake 1.2 has a significant improvement over Validation. Its added more built in validation roles which are great. Now it supports alphanumeric, email, maxlenght, url and phone validations.

More about Cake validations are here: http://cakebaker.42dh.com/2007/01/03/validation-with-cakephp-12/

Data validation in CodeIgniter is handled via a validation class. A set of rules get defined and assigned to the validation object. The validation object automatically validates the data passed via the URL or form. From there, you can decide how that gets handled. The validation class can also help automate some of the process of setting error messages for specific fields.

Documentation: CodeIgniter is well documented. This is why I always tell a starter to start with CI. CI also has forums and a wiki which feature a lot of user-submitted code.

On the other hand Cake’s manual is not that strong against CI’s documentation. Manual says enough but I don’t think it’s enough for a newbie to get familiar with all sort of things that cake’s API says.

Well, this is where my post is finished. I know all these things that I have said not enough to find all similarities and dissimilarities of Cake and CI. So I would like to ask you to correct me if I made any mistakes or understood anything wrong according to my description. You can tell me to add more in the post. Your any comment will be welcomed.

Thanks a lot 🙂





Both of these PHP Frameworks follow model-view-controller architecture. This is why both of them got lots of things in common but at the same time they have some dissimilarity too. I was thinking to make a list of all those similarities and dissimilarities with some small examples so that when I move one framework to another, it can remind me the dissimilarities. I have pointed out some main features of these 2 frameworks to discuss about.

Installation: well, both of them got similar installment process. Like CodeIgniter installation in 4 steps.

  1. Unzip the package.
  2. Upload the CodeIgniter folders and files to your server. Normally the index.php file will be at your root.
  3. Open the application/config/config.php file with a text editor and set your base URL.
  4. If you intend to use a database, open the application/config/database.php file with a text editor and set your database settings.

This installation process is same for Cake “development setup”. But we don’t have to setup any URL for Cake.

Dissimilarities come when we want to increase security hiding our location. CI’s system folder can be renamed into something private. But in this case $system_folder variable name has to be changed from inex.php file into chosen name of the folder. CakePHP has 2 more installation process, these are: using a development setup, which allows us to easily view many CakePHP applications under a single domain, or using the production setup, which allows for a single CakePHP application on the domain.

Although both of their installations are very easy but comparing these two, I guess CI’s installation process is easier.

Scaffolding: I wrote a blog on Cake Scaffolding and CodieIgniter Scaffolding. I’m gonna say the same thing here, so let me just paste it here:

In cake Once you add this variable called $scaffold in your controller it gives an idea about early parts of development of your application.

Example: <?php

class YourController extends AppController


var $scaffold;



But what if you forget to take it off before you up the project in real server and somebody guesses your URL? Well certainly scaffolding has edit and delete option right. So it’s not secured I guess.

I like how CodeIgniter is dealing with scaffolding. Almost same but there is an option for you to set secured scaffolding. You have a secret word option which will be set here:

application/config/routes.php in CI like this

$route [‘scaffolding_trigger’] = ‘ sewt ‘; //assume your secret word is “sewt”

So now use your scaffolding in the controller

class YourController extends Controller {

function Test()


To see this scaffolding you have to follow this URL path:


Isn’t it better eh?

Default Layout: CakePHP uses default layout, the layout has two variables by default: title_for_layout and content_for_layout. Each action automatically links to a particular view which gets spat into place. This is simply great to use for many pages. Once default page is setup, boring stuff like adding header and footer again and again completely gone.

CodeIgniter doesn’t have any default layout! I feel this is bad side of CI that it doesn’t have any default layout like Cake. It’s like row php code where I have to include header, footer each and every time I create a new file. To help on it I guess this post is really helpful, have a look here: http://hasin.wordpress.com/2007/03/05/adding-yield-codeigniter/#comment-55979

Model: first of all, I would like to give an example of a CakePHP model.

class User extends AppModel
var $name = ‘User’;
var $hasOne = array(‘Profile’ =>
array(‘className’ => ‘Profile’,
‘conditions’ => ”,
‘order’ => ”,
‘dependent’ => true,
‘foreignKey’ => ‘user_id’

Here, Variable name (‘User’) must start with Capital letter and table name must be plural (‘users’). This is a strict convention that Cake follows.

One of the most powerful features of CakePHP is the relational mapping provided by the model. In CakePHP, the links between tables are handled through associations. Associations are the glue between related logical units.

There are four types of associations in CakePHP:

1. hasOne

2. hasMany

3. belongsTo

4. hasAndBelongsToMany

When associations between models have been defined, Cake will automatically fetch models related to the model you are working with. For example, if a Post model is related to an Author model using a hasMany association, making a call to $this->Post->findAll() in a controller will fetch Post records, as well as all the Author records they are related to.

In codeIgniter there are no model associations. There is no strict naming convention. Although class name must be capitalized. Let see an example if CodeIgniter model:

class Blogmodel extends Model {

var $title = '';
var $content = '';
var $date = '';

function Blogmodel()
// Call the Model constructor

function get_last_ten_entries()
$query = $this->db->get('entries', 10);
return $query->result();


So, query in CI is almost like writing SQL command. I feel this is better in a sense that my query is optimized here. It searches exactly what I need. In Model association concept I saw many unnecessary results that I didn’t ask for. But sometimes I feel I can call CodeIgniter as VC pattern framework, because I can do almost  the same work of model in Controller 🙂

Ok, that’s all for today ….if you have any complains/comments/suggestions please write it down. I’m coming up with more similarities and dissimilarities in my next post……




Use one config file: well, I had this bad experience recently. I was assigned to a project which was done by row php and I was supposed to fix the bugs of the project.  So I got the project and installed in my laptop. This is where main problem begun when I started changing configuration files!! I gave up after changing 16 config files! How come you can use individual config file?? You gotta keep one config file for the whole project.  But you don’t have to worry about it if you’re using a php framework. 

You should develop something that other developer can read it easily and understand easily.

Keep “Error reporting” on: Sometimes you see a blank page without any error. You are probably thinking what the hell is wrong with your code???

If you want to make your testing phase easy then you gotta work keeping your Error reporting on. Personally I found it’s really helpful, hence you know exactly what’s going on the project and where you made the mistake. You can use different kinds of error reporting options but I recommend you to use this below error reporting function at the top of your php page.



ini_set('error_reporting', E_ALL);

Use print_r() :

I found it’s really helpful to see actually what is going on with your variable/array. If you are not familiar with this function let me give you a definition from PHP manual:

 print_r() displays information about a variable in a way that’s readable by humans. If given a string, integer or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements.

Let say you have an array like this

$a = array (‘a’ => ‘apple’, ‘b’ => ‘banana’, ‘c’ => array (‘x’, ‘y’, ‘z’));

Ptint_r($a) will certainly print your array but let me give you a tips to see your array nicely organized. Use HTML tag <Pre> before you print your array. So example will be like bellow:

    $a = array (‘a’ => ‘apple’, ‘b’ => ‘banana’, ‘c’ => array (‘x’, ‘y’, ‘z’));
    print_r ($a);

 And output will be like this:



    [a] => apple

    [b] => banana

    [c] => Array


            [0] => x

            [1] => y

            [2] => z



  You can also use var_export(), and var_dump() for similar reason. And well, this is more helpful when you work on a developed application. Certainly you don’t know all data process that was developed by other devs. Print_r() helps you to recognize all values that are passing through your current page.

Use manual: I saw many PHP developers who don’t use PHP manual. To me its kind of strange thing! How come you don’t use the best Manual in the world!? I have never seen a Manual so organized and fulfilled like PHP manual. What you want from there? It’s always better to learn by yourself and in that case none but PHP manual is your best friend. Just download the latest version of PHP manual if you are using PHP 5 and start reading from the beginning. I can bet you will love it even if you are not a PHP developer.

Use long tag: Both short tag and long tag being used extensively. But your webhost must enable the short tag (<? =)  in php.ini to make it run. To make your application safe you better use long tag (<?php echo “”)

Separate your HTML part: You may include HTML parts that you reuse across pages like the navigation, header, footer etc. I guess, instead of coping and pasting same code for similar pages you better make a separate file for them and later you just can add them in your page according to the need.

Make your application location independent: I got this experience recently from my foreign project. Your local directory and my local directory might not be same. And when you up the project in the real server that’s also not same right. So you must try to make your directory configuration independent.

 Let me give you an example:

$absolute_path = ‘D:\xampp\htdocs\yadda\gadda;  //assign changing part in a variable

require_once(“$absolute_path /lib/something.php “); //then just use it like this. So that next time you don’t have to change each line instead you just have to make change on one line. It’s similar like keeping one config file instead of several.

PHP coding standard: Try to follow a PHP common standard so that life becomes easier for other developers. You may follow your own style of coding but you have to keep it in mind that you’re not the last developer for the project you’re working on. Make sure new people can get what you have meant with your code. Make sure programmers can go into any code and figure out what’s going on. To do so you must wrote your code following a standard and common PHP coding. To get some clear idea please some goggling.

Use a framework: uhm…ya of course this is a part of good practice. Once you have general idea about PHP you can move to a PHP framework and that should be MVC patter follower (i.e. CakePHP and CodeIGniter). If you use a framework, most of the problem I mentioned above will be solved! Built-in functionality will make your life easier I can tell you.

Well that’s all from me. I know I have missed a lot of good practices here. All I have written from my little experience with PHP. Please feel free to suggest me more good practices for PHP developers.

View Junal Rahman's profile on LinkedIn
Subscribe to me on FriendFeed

Follow Me on Twitter


My photos

Blog Stats

  • 425,753 hits