Junal on the run

Archive for the ‘CodeIgniter’ Category

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:

$url=getimagesize(“http://www.flickr.com/photos/27505599@N07/2564389539/”);

if(!is_array($url))

{

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

}

Advertisements

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.

strrev()

–          This will reverse the given string

Example:

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

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

strtok()

–          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 :

Word=Junal
Word=is
Word=being
Word=tokenized

ucfirst()

–          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!

Example:

$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 🙂

idate()

–          Format a local time/date as integer

Example:

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

echo idate(‘m’, $timestamp);

Output: “2”

Array Functions

Array_diff()

–          Computes the difference of arrays.

–          Example :

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

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

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

print_r($result);

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.

array_product()

–          Calculate the product of values in an array

Example:

$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.

I was searching a Facebook application example with CodeIgniter today. There weren’t many tutorials on it so decided to give a try for FB application with CI. So let’s see what and how I did it.

I’m assuming you know how to setup a FB application. If you don’t then please visit here, this is a great step-by-step process to start a FB application.

Well, if you are done setting up the process according to the instruction, you supposed to have few things in your hand: an API key, Secret key, Callback URL and base URL.

Now you need to Download the latest version of CodeIgniter and unzip the folder in your Base URL location. Set base URL from application/config/config.php

Example : $config[‘base_url’] = “http://apps.facebook.com/your-app-name/”;

Ok, now set your default controller from here: application/config/routes.php

Default controller is “welcome” – for sample application I didn’t change it. I just worked on default controller. You can change it according to your needs. If you want to use different controller keeping default controller as it is then add that controller name to your Callback URL.

Now let’s download the Facebook client library from here:

Once you have this package in your hand place them in your application/plugins (if there is not folder named plugins then create it) folder. Note that, you can also add the library in the library folder.There are only three files of FB client library- place them in your plugins folder. But don’t forget to rename your facebook.php to facebook_pi.php

Yay ! We are done all initial setting stuffs. Now need to see some actions!

Open you default controller (in my case “Welcome” controller).

First of all we need to create a __Contrust class so that it gets initiated for the first time application user.

So our construct class will be look like this:

  class Welcome extends Controller {
  var $facebook;
  //API and secret key that you got from your application setup.
  var $__fbApiKey = 'YourKey';
  var $__fbSecret = 'YourSecretKey';

function __construct()
{
parent::__construct();
  //load the client library that we added as plugin in plugins folder.
  $this->load->plugin('facebook');
  // Prevent the 'Undefined index: facebook_config' notice from being thrown.
  $GLOBALS['facebook_config']['debug'] = NULL;
  // Create a Facebook client API object.
  $this->facebook = new Facebook($this->__fbApiKey, $this->__fbSecret);
  $user = $this->facebook->require_login();
}
	function Welcome() {
		parent::Controller();
	}
	// You should place your Controller's methods below.
function index()
{
   // Retrieve the user's friends and pass them to the view.
   $friends = $this->facebook->api_client->friends_get();
   $this->load->view('welcome_message' , array("friends"=>$friends));
}

So we have called Facebook API key and secret key and then we loaded the client library that we added as plugin in plugins folder. At the end we checked if the user is logged in or not. Well, you can avoid it by defining a Session key. But I found it was easier to avoid Session key problem with the application by allowing users logged in first.

We supposed to get connected with FB API by this time. So let’s play with FB API now. Create a function called index () and lets retrieve logged in user’s all friends from it.

So it should look like this

function index()
{
   // Retrieve the user's friends and pass them to the view.
   $friends = $this->facebook->api_client->friends_get();
   $this->load->view('welcome_message' , array("friends" , $friends));
}

So we got our friends list in “friends” array. Let’s go to “welcome_message” view in view folder to retrieve and show all friends that the array is containing. My view looks like this bellow.

<h3>Welcome to Sample Facebook application with CodeIgniter!</h3>
<div class="container">
< ?php
foreach ($friends as $id)
{
?>
<div class='img'>
	<fb :profile-pic uid='<?=$id?>' firstnameonly = 'true' linked='true' size='square'/>
<div class='name'>
		<fb :name uid='<?=$id?>' firstnameonly = 'true' capitalize='true'  useyou = 'false'/>
	</fb></div>
</fb></div>
< ?php
}
?></div>

Two facebook tags are added here. One is for Profile picture of my friends and second tag is to show my friends name. I have also added three more CSS class to show it a little bit better.
Examples Output

They are:

 .img {
  float: left;
  padding : 10px 0px 0px 10px;
  width:50px;
  overflow: visible;
}

.name {
  padding-top: 0px;
  text-align: center;
}

.container
{
  padding-left:18px;
}

You can add this at the top of your view page in the <style> tag.

Now let’s go to the FB canvas and see what is my page is showing. From the above example my canvas page shows the output like this:

Okay, if you want to add database, you just need to configure your application/config/databse.php file. Rest of the things are same.

Ahh ! It’s cool. I guess if I use any FW for FB application first I will check the volume of the application. I think there is no meaning to use FW for a small FB application.

Update: This post is updated on 2nd Apr 2010. Thanks @gevork for updating the code.

Well, finally I have finished reviewing this first book. I’m sorry that its being long time since I got the book on my hand. Was really busy with some project deadlines, as a result I couldn’t continue on it after first 3 chapters. Anyways, today I have finished reviewing this book, so let’s see what I have found interesting from this book. Let’s go through each chapter.

CodeIgniter for Rapid PHP Application Development

Chapter 1: Introduction to CodeIgniter: First chapter will give you a good idea how CI can reduce your lots of code comparing to ROW PHP. A little bit idea about Framework as well. Although I felt – it should have been a little bit more and a picture of the author on this chapter was really unnecessary.

Chapter 2: Two minutes work: Setting up a CodeIgniter Site: a very little chapters on how to install CI. I guess CI user guide has got the same thing – although there is nothing much to talk about CI installation.

Chapter 3: Navigating Your Site: when I was reading this chapter, I felt like I wanted to read about Framework concept too earlier. This is a great chapter on Controller and View- it gives some idea about CI’s controller. But I didn’t like writings on “Types of files on classes on a CI site”- because it looks messy. Maybe it should have written more clearly. Except that everything of this chapter were wonderful.

Chapter 4: Using CI to Simplify Database: an excellent description on how Active record saves your time and makes everything organized. Even if you don’t know what is called Active record , this chapter will make you understand it easily.

Chapter 5: Simplifying HTML pages and Forms: Liked all description about HTML view but really wanted to see a complete different chapter on VALIDATION. Writer should have written more on Validation. I found description wasn’t enough on Validation.

Chapter 6: Simplifying Sessions and security: Nicely explained about SESSION and SECURITY. But one thing came in my mind that there should have been some ordered in chapters as we see in the manual. Well it was writer’s choice but still I didn’t see any complete explanation of the CI framework yet!

Chapter 7: CodeignIter and Object: This is the chapter that actually describes how CI works. If you are a newbie I guess you can skip it. This chapter gives you some idea about OOP and a clear idea on “Super-object”.

Chapter 8: Using CI to test Code: Yay!! This is what I really wanted to see. Even if you don’t like other things of this book, I guess you can buy this book just for this chapter! This is a complete description of code testing including Unit test. I didn’t want to use Unit test before just because it was too much time consuming. But I guess CI can make it easier and this chapter adds more on it.

Chapter 9: Using CI to communicate: another great chapter! A clear idea on XML-RPC with a cool example. People, who are not familiar with XML-RPC, will get a good idea about it.

Chapter 10: How CI helps to provide Dynamic Information: well, mainly about helpers. I guess user guide has all these informations.

Chapter 11: Using CI to Handle Files and Images: If you want to know how to handle image and files with CI – this chapter is a great explanation for that.

Chapter 12: Production versions, Updates, and Big Decisions: Very needy information especially for production version. A great discussion on some common errors that are actually often occurred on production version.

Chapter 13: Instant CRUD – or Putting it all Together: A complex and boring chapter. Unnecessary codes without proper explanation. A better description is given in User guide on CRUD. It was really boring to read!

Chapter 14: The Verdict on CI: I liked this chapter. I liked the honesty of the author. I guess title of this chapter says what it is about.

Chapter 15: Resources and Extensions: mainly all needy links that contains information about CI. Well- I guess goggling will give you better results for it.

That’s it! Personally, I like this book for:

  • Chapter 3: Navigating Your Site.
  • Chapter 4: Using CI to Simplify Database
  • Chapter 8: Using CI to test Code
  • Chapter 9: Using CI to communicate
  • Chapter 12: Production versions, Updates , and Big Decisions
  • Chapter 14: The Verdict on CI

I guess these are enough reasons to buy this book. Although CI has one of the strongest documentation but I guess people who want to know about Unit testing with CI, XML-RPC with CI can buy this book. Plus a book is always a better explanation than just the documentation.

I missed one thing that writer should have given a complete example with screenshot. Like a blog tutorial is given in the manual. There are some examples given, but I felt it wasn’t enough. Few more screenshot of the examples should have been taken.

It will be a little bit difficult [as writer said] to read this book if you are a newbie and don’t have any idea about PHP. To read and understand this book you should have some good idea PHP, only then you can get 100% out of this book.

Mr. Duane Moraes is a Marketing Account Executive of Packt publications who emailed me like 2 weeks ago asked me if I was interested to review 2 PHP books. Well, I was glad to receive that email from him and I emailed him back saying that I would love to review them. These 2 books are:

  1. CodeIgniter for Rapid PHP Application Development and
  2. PHP Web 2.0 Mashup Projects

CodeIgniter for Rapid PHP Application Development   PHP Web 2.0 Mashup Projects

I’m so happy that today, I have received them! So, I’m gonna start reviewing these 2 books. I will start with “CodeIgniter for Rapid PHP Application Development” and of course I will let all of you know about this book. I’m pretty sure I’m gonna enjoy these books because i love PHP and CI is one my favorite PHP framework.

Well, I would like to thanks Mr. Duane for considering me as a reviewer of these book.

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:

<?php

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:

http://codeigniter.com/wiki/AJAX_for_CodeIgniter/

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.

application/config/autoload.php

Example:

$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 🙂

References:

http://codeigniter.com/user_guide/

http://manual.cakephp.org/

http://snook.ca/archives/php/codeigniter_vs_cakephp/


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

Follow Me on Twitter

Archives

My photos

Blog Stats

  • 423,253 hits