nav-left cat-right
cat-right


Taking Zend Framework workshop on Dec, 09

Bbjobs has arranged a workshop on “Zend framework fundamental” on December, 09  and invited us (me and Emran Hasan) to take it. We agreed happily. This is (so far I know) the first formal Zend Framework workshop in Bangladesh. The workshop has been defined as -

The Zend Framework Workshop is a 5 half-day tutorial-style course that takes an in-depth look at Zend Framework and its components. The workshop is designed for experienced PHP programmers who want to learn to combine ZF concepts and structural elements to utilize the full power of this software development kit for PHP 5 applications.

As per our plan about the context of this workshop, we are going to cover the following 8 basic topics of Zend Framework in 5 days.

(more…)

Book review: PHP Team Development

PHP Team DevelopmentThree weeks ago, I was contacted by Packt publishing asking if I’d review their new book “PHP Team Development” by Samisa Abeysinghe. I agreed and received the book. But, after reading it, I was wondering about how to tell negative things politely.

In the mean time Lorna Jane, Brandon Savage, Ken Guest, Walter Ebert and some other people wrote their review about this book. And I found, most of their opinion supports my thoughts on it. Actually, most of the things that I thought has already been said in their posts. So, I am not going to repeat them and will tell my views shortly.

This book will introduce teamwork and some development processes (XP, Scrum) to fresh devs . It has brief introduction about source control, bug tracking, continuous integration and many other important terms of software development. These may help a beginner who have made software for university assignments but never worked in a professional team. The author had intention to describe the complexity and some commonly occurring problems of software development with suggesting solutions.

It presents MVC as the way of working of a team and tried to solve everything(!) with it. As some others mentioned, the author has presented his solutions as the only way of doing something. It didn’t enlighten the readers about other available solutions. Also, a few of the topics did not seem to be related with the context of this book title.

This book mentioned about many tools, processes and methods – but most of them are not explained up to such a level that one can implement them after reading the book. Some concepts of the book seemed unrealistic to me. For example, separating teams based on concern (one team will work with model, another with view; and tie them up together later).

Like Walter Ebert said, this book seems to be a “quick ‘n dirty guide on team development” to me. About recommendation, I’d say, if you are a beginner in PHP (also in programming) and just know how to connect and retrieve data from MySQL, then the book can help you know many of the terms which you should study next. If not, then you should spend some time on finding a better book to start with.

Simple PHP PDO Wrapper : light, static, easy

A few days ago, I was looking for a PDO wrapper to work with a small PHP application. I’ve searched around and found fractalizer’s PDO wrapper nearest to my purpose. Then I just wrote my wrapper on the shadow of his one.

Let’s see what’s inside and how it works.

Features

  1. Easy to use.
  2. Works with MySQL and Sqlite.
  3. All pubic functions works statically.
  4. Connection string created internally.

Download files

Download the PHP PDO wrapper (downloaded 1443 times).

The download archive includes -

  • Db.php – the PDO Wrapper class.
  • DbTest.php – Unit testing class for Db.
  • DbExample.php – Example of some common uses.
  • Some other unit test related files.

(more…)

Advanced bootstrapping : Configure your Zend Framework application for multiple host

This tutorial is intended to explain a way of bootstrapping Zend Framework based MVC application for multiple host/domains. Before starting, let me explain a bit about the situation when it’s needed.

A web application goes through some stages when growing up. Generally, it starts from development and ends at production. There can be some more stages within this two ends. And, in maximum cases this stages are overlapped. The overlapped stages can be hosted in different servers with different settings but shares the same code. In this situations, if we want to keep bootstrap in SVN repo, it needs to setup bootstrap in a little different way. So that, it can handle many server settings with a single bootstrap.

For example, just now I am working on an application which is being developed in 3 local machines (me and two other members of my team) and being tested in our staging server. Besides, our client is monitoring progress of current sprint in their staging server and testing completed sprints in their pre-production server. Here, except the production servers, all hosts contains a checked out copy of code from a single repository. But this hosts have some difference in their library path, database host and authentication etc.

If my assumptions are ok for you, let’s start after downloading.

Assumptions


I have assumed that you are familiar with Zend Framework. And already worked on (atleast one) ZF MVC application. You know the basic things about bootstrapping and using the most common directory structure (shown in image). However, you can tune this technique for your favorite Zend directory stracture.

Download files

Downoad the files from here. The zip file contains -

  1. index.php – This is the bootstrap file. Your .htaccess file points all request to this file.
  2. config.xml – Contains all configurations of your application, for all hosts.
  3. Bootstrap.php – A php class that handles all startup settings in a vary organized way. (I don’t know who first wrote it, Thanks to him)

(more…)

PunBB modification – Implementing iconized categories for forum topics

PunBB is one of the fastest and minimal forum softwares powered by PHP. PunBB says about itself:

PunBB is a fast and lightweight PHP-powered discussion board. It is released under the GNU General Public License. Its primary goals are to be faster, smaller and less graphically intensive as compared to other discussion boards. PunBB has fewer features than many other discussion boards, but is generally faster and outputs smaller, semantically correct XHTML-compliant pages.

You can see a detailed review about PunBB from forum-software.org.

What’s the purpose this mod?

PunBB has categories for forum. But there is no categorization for Topics like many other forums. This mod implements an iconized category for topics. The end result of this mod is -

  • It will add an excellent looking “Category Icons” fieldset in “Post new topic” form. (see Image#1)
  • Users can (optionally) select a topic category while posting a topic.
  • The category icon will be displayed beside the topic title in forum index page, topic detail page, search result etc. (see Image#2 and Image#3)
  • Clicking on a category icon will show all topics under that category.(see Image#4)

Lets see some screenshot of this modification :

Category icons in "Post new topic" form

Image#1:  Category icons in Post new topic form

Category icons before topic title in forum page

Image#2: Category icons before topic title in forum page

FireShot Pro capture #5 - 'User Contributed Deals _ Television is poluting our culture' - local_deals_com_forum_viewtopic_php_id=5

Image#3: Category icon in topic page

FireShot Pro capture #7 - 'User Contributed Deals _ Search results' - local_deals_com_forum_search_php_search_id=1345131291

Image#4: Filtering by category

(more…)

Image manipulation in Zend Framework using PHP Thumbnailer Class v2.0

In the huge set of library, Zend Framework have no options for manipulating image. There is a proposal for Zend_Image which aimed to provides easier image manipulation using GD. But the proposal was not considered. Bill Karwin of ZF said,

Proposal not being considered

This proposal has been reviewed. The proposal describes functionality that is very similar to the existing PHP interfaces for ImageMagick or GD.

We are not considering this for inclusion in the Zend Framework at this time.

So, what to do when we need to make image thumbnail, resizeing or cropping image etc in Zend Framework?

The Solution

Zend Framework has the extensive power of integrating any library. So, we can use ImageMagick or GD library or any wrapper class using this libraries for manipulating image.

Here, I am explaining creating image thumbnail using PHP Thumbnailer Class v2.0 in 2 easy steps. I am assuming that, you are using Zend’s MVC with common directory structure and you’ve GD library with your PHP installation.

Step 1 – Create a Model for image manipulation :

Download the PHP5 version of PHP Thumbnailer Class v2.0 and put the class file “thumbnail.inc.php” in your model directory. Now change the file name to “Thumbnail.php” as it’s class name. Now your model is ready for action.

Step 2 – Use this model in Controller :

In your Controller, write a function to make thumbnails using this model. For example, you can use this function below:

   1: /**
   2:  * Create thumbnail of an image
   3:  * 
   4:  * @author    Anis uddin Ahmad (http://www.ajaxray.com)
   5:  * @param     string    Path of source image
   6:  * @param     string    Destination path of thumbnail
   7:  * @param     number    Width of thumbnail
   8:  * @param     number    Height of thumbnail
   9:  * @param     number    (optional) thumbnail image quality 
  10:  */
  11: private function _createThumbnail($sourcePath, $destPath, $w, $h, $q = 100)
  12:  {
  13:     $thumb = new Thumbnail($sourcePath);
  14:     $thumb->resize($w, $h);
  15:     $thumb->save($destPath, $q);
  16:  }

Done. Now you can use this function to resize/make thumbnail of an image. To resize an image with keeping it’s original name, pass the $sourcePath again in $destPath parameter. Then it will overwrite the existing image.

So, was it so though to manipulate image in ZF?

Join Problems with Zend_Paginator and Zend_Db_Select objects

Zend_Paginator is one of the newest members of Zend framework family. It’s surely a rich addition with Zend’s power. Moreover, It’s handling the main data of pagination, not only pagination links. Which I didn’t found in any other pagination library.

But, when I (and many other developers) start to working with this library, found many problems/bugs. The matter is, they are being solved very fast and hope to get a bullet-proof pagination library soon. For example, here is tow important fixings about Zend_Paginator and Zend_Db_Table_Select.

I had to face a problem with Zend_Paginator when using Join in Zend_Db_Select object. I am explaining here how the problem arises and how to solve it.

The Problem

One of the 4 Adapters for Zend_Paginator is DbSelect which uses a Zend_Db_Select instance. Now, the problem occurred if I need to have some calculative data from other tables and use join with the Zend_Db_Select object for them. For example, I am retrieving data from `deals` table and collecting number of comments from `comments` table and total votes from `votes` table. So, with other conditions, I had to add this lines with select object:

   1: $select->joinLeft(array('c' => 'comments'), 'deals.id = c.deal_id', array('total_comments'=> 'count(c.id)') );
   2: $select->joinLeft(array('v' => 'votes'),    'delas.id = v.deal_id', array('total_votes'   => 'count(v.id)') );
   3: $select->group($this->_name . '.id');

 

Now, the Zend_Paginator will always calculate the TotalRows as 1. That means, $this->totalItemCount; will always print 1 in “view partial“.

Why it happens?

Let’s take a look to the count function of DbSelect Adaptor of Zend_Paginator:

   1: public function count()
   2: {
   3:     if ($this->_rowCount === null) {
   4:         $expression = new Zend_Db_Expr('COUNT(*) AS ' . self::ROW_COUNT_COLUMN);
   5:         
   6:         $rowCount   = clone $this->_select;
   7:         $rowCount->reset(Zend_Db_Select::COLUMNS)
   8:                  ->reset(Zend_Db_Select::ORDER)
   9:                  ->reset(Zend_Db_Select::LIMIT_OFFSET)
  10:                  ->columns($expression);
  11:                  
  12:         $this->setRowCount($rowCount);
  13:     }
  14:  
  15:     return $this->_rowCount;
  16: }

Here, at line 7, the column list is being removed. But we have a `Group By` clause in our select object which is not cleared by this function and the result is always 1. At this point, if we add “->reset(Zend_Db_Select::GROUP)” after line 9, the calculation will get rid from always being 1. But there will arise another problem. That is, joined tables are still remaining in `From` clause. You can see them by adding “die(print_r($rowCount->getPart(Zend_Db_Select::FROM)));” after line 10. This join tables will make the calculation inconsistence because there is no expression columns now to summarize their result.

The Solution

Just alter this function as following to prevent this problem:

   1: public function count()
   2: {
   3:     if ($this->_rowCount === null) {
   4:         $expression = new Zend_Db_Expr('COUNT(*) AS ' . self::ROW_COUNT_COLUMN);
   5:        
   6:         $rowCount   = clone $this->_select;
   7:         $rowCount->reset(Zend_Db_Select::FROM);
   8:         
   9:         foreach($this->_select->getPart(Zend_Db_Select::FROM) as $name => $table)
  10:         {
  11:             if(empty($table['joinCondition']))        
  12:             {
  13:                 $rowCount->from(array($name => $table['tableName']));
  14:             }
  15:             elseif($table['joinType'] == 'inner join')        
  16:             {
  17:                 $rowCount->join(array($name => $table['tableName']), $table['joinCondition']);
  18:             }
  19:         }
  20:         
  21:         $rowCount->reset(Zend_Db_Select::COLUMNS)
  22:                  ->reset(Zend_Db_Select::ORDER)
  23:                  ->reset(Zend_Db_Select::GROUP)
  24:                  ->reset(Zend_Db_Select::LIMIT_OFFSET)
  25:                  ->columns($expression);
  26:  
  27:         $this->setRowCount($rowCount);
  28:     }
  29:  
  30:     return $this->_rowCount;
  31: }

At line 9, I am running a foreach which will remove the `from` clause and again assign only the main table and inner join tables. And, at line 23, just removing the `Group By` clause from query. Now, this function will provide right calculation even when there is some joins like this. But, if you use inner join in your Zend_Db_Select object (which is very rare for pagination), this function may not serve properly.

If there is any mistake in this alternation or any other way can make it better, please let me know. And… let’s meet power with simplicity.

UPDATE [26/08/08] : The function is updated and hopefully it will work fine for inner joins too.

UPDATE [24/09/08] : This issue is solved in ZF 1.6. Jurrien Stutterheim has reported about this post in Zend Framework Issue tracker and worked on it. After the release of 1.6, he requested me to check if this issue still exist. I’ve checked and found it solved. Thanks to Jurriën Stutterheim.

Developing web application with PHP-MySql-Apache in Ubuntu Linux

I have started using Ubuntu 8.04 in few days ago and found it Great. So, now I’ve moved my development environment from windows and working in Ubuntu. Here I am just explaining what steps I had to take for this jump. Also have a listing of some development related softwares/tools which I am using as replacement of windows applications.

Installing Apache, Php5, MySql in Ubuntu:

You can install Apache, Php, Mysql and other applications from Synaptic Package Manager. Go to System > Administration > Synaptic Package Manager and search with your desired application name. When found, double-click on package name. The package will be marked for installation along with it’s dependences. Now click on apply button to install the package. In this post, the red+bold texts are the name of software package which can be installed from Synaptic Package Manager.

To make your system ready for PHP development, you have to install more or less this packages: apache2.2-common, apache2-utils, php5, mysql-server-5.0, mysql-client-5.0, mysql-query-browser etc. You may also require some common php extensions which may not installed automatically with PHP installation. Most of them also will be found in Synaptic Package Manager as php5-gd, php5-curl, php5-mysql, php-pear etc.

Paths of important directories

One of the major differences I find here is the file system. All the directory paths I’ve been using in windows are changed here. I m listing here some PHP-MySql related paths here. But they may differ on your installation.

  • Apache configation files: /etc/apache2/
  • localhost root directory: /var/www/
  • PHP ini file: /etc/php5/apache2/
  • PHP extensions configuration files : /etc/php5/conf.d
  • MySql Data files: /var/lib/mysql/mysql
  • MySql Configuration files: /etc/mysql/

PHP Editors for Ubuntu

Gedit is the default text editor of Ubuntu and it support syntax coloring for many languages including PHP. But If you want an advanced editor for programming, you can try Geany or Screem. But, I am sure, who’ve been using advanced IDEs like PHPEd or PHPDesigner in windows, none of this can satisfy him. Don’t worry, the great open source IDE eclips has PHP-Development-Tool. It’s surely one of the best PHP IDE.

Subversion in Ubuntu

Subversion maintains current and historical versions of source code and documentation. It’s very important for distributed application development. RapidSVN is a graphical client for the subversion revision control system (svn) for linux. If you want to use svn from command line, install subversion.

File Difference and Merging Tools for Ubuntu

I have been using WinMerge in windows as file comparison and merging tool along with TortoiseSVN. Now using TkDiff as it’s alternative in linux. TkDiff has advanced functionalities and graphical interface. It provides file-merge and change-summary facilities, line number toggling (for easier cut & paste) and support for Subversion, RCS, CVS and SCCS. To use from command line, diff is may be the simplest file comparison tool.

Ftp and SSH

Ubuntu installs its default programs for FTP, SSH and many other internet applications. But, I’ve liked gFTP as FTP application because of it’s interface is similar to SmartFTP. And for working with SSH, required nothing. Just open the terminal and use ssh command. Write something like ssh username@example.com and press ENTER.

Testing in IE

One of the important (and painful to me) issue of web development is testing the output in IE. Though IE has no version for Linux, you can install it through wine. Wine is a application that crates a virtual environment for installing windows applications in Linux. After installing wine, you can install any available version of IE from http://www.tatanka.com.br/ies4linux/page/Installation:Ubuntu.

When witting this post, my aim was to help a developer who is thinking to switch to Ubuntu Linux or a newcomer here. You are welcome to add your valuable comment/suggestion for the same purpose.

PHP Universal Feed Parser – lightweight PHP class for parsing RSS and ATOM feeds.

After the PHP Universal Feed Generator, I’ve written the PHP Universal Feed Parser for Orchid Framework. It’s a RSS and ATOM parser written in PHP5. Though there are many feed parsers over Internet, none of those was serving the basic focuses of Orchid: pure object orientation, being lightweight etc. So, I had to write a new one.

UPDATE(15th May, 2008) : cURL support added. Where url fopen() is disabled, the class will use cURL to load the RSS/ATOM content.

Features:

  • Parses all channels and feed item tags and sub tags.
  • Serve the parsed data as associative array.
  • Enough documented and easy to understand code.
  • Many ways to get parsed information.
  • Parsing includes attributes too.
  • No regular expression used.
  • Parsed by XML Parser extension of PHP.
  • Pure PHP5 objected oriented.
  • Enable to parse all commonly used feed versions.

Supported versions: I tried to include all stable and commonly used feed versions. Currently it’s being used to parse the following versions:

  • RSS 1.0
  • RSS 2.0
  • ATOM 1.0

Download:

  • Click Here to get the class file with example. (downloaded 4038 times)
  • Download from phpclasses.org.

How to use:

It’s dead simple to use this class. Just follow this 3 steps:

1. Include the file

include(’FeedParser.php’);

2. Create an object of FeedParser class

$Parser = new FeedParser();

3. Parse the URL you want to featch

$Parser->parse(’http://www.sitepoint.com/rss.php’);

Done.

Now you can use this functions to get various information of parsed feed:

  • $Parser->getChannels() – To get all channel elements as array
  • $Parser->getItems() – To get all feed elements as array
  • $Parser->getChannel($name) – To get a channel element by name
  • $Parser->getItem($index) – To get a feed element as array by it’s index
  • $Parser->getTotalItems() – To get the number of total feed elements
  • $Parser->getFeedVersion() – To get the detected version of parsed feed
  • $Parser->getParsedUrl() – To get the parsed feed URL

A simple example:

Here is a simple example of using this Feed Parser class. Click here to see is the output of this example.

<?php
include('FeedParser.php');
$Parser     = new FeedParser();
$Parser->parse('http://www.sitepoint.com/rss.php');

$channels   = $Parser->getChannels();
$items      = $Parser->getItems();
?>
<h1 id="title"><a href="<?php echo $channels['LINK']; ?>"><?php echo $channels['TITLE']; ?></a></h1>
<p id="description"><?php echo $channels['DESCRIPTION']; ?> </p>

<?php foreach($items as $item): ?>
    <a class="feed-title" href="<?php echo $item['LINK']; ?>"><?php echo $item['TITLE']; ?></a>
    <p class="feed-description"><?php echo $item['DESCRIPTION']; ?></p>
<?php endforeach;?>

I hope, this class is so easy that, anyone who have general knowledge about PHP5 can use it. Whatever it is, Feel free to ask me anything, anytime.


Note : Hi all, I’ve reported about some situations from users where this class is not working properly. So, I’ve decided to re-write it ASAP. Hope the next one will be more powerful, smaller in size and easier to use.
     — Thanks.

PHP Universal Feed Generator (supports RSS 1.0, RSS 2.0 and ATOM)

It’s been a while since I’ve planned on developing a RSS writer that fulfills most my needs by supporting the various feed formats. Although the necessity was the prime force behind it, a discussion with Hasin and Emran has put the actual fire in. We were discussing about what can be added next in the Orchid – “PHP framework for the rest of us” and suddenly it hit me. At last, it’s finally complete and I’ve named it "PHP Universal Feed Generator", as it generates both ATOM and RSS feeds.

Supported versions:

  • RSS 1.0 (which officially obsoleted RSS 0.90)
  • RSS 2.0 (which officially obsoleted RSS 0.91, 0.92, 0.93 and 0.94)
  • ATOM 1.0

Download: 

Features:

  • Generates RSS 1.0, RSS 2.0 and ATOM 1.0 feeds
  • All feeds are are validated by feed validator.
  • Supports all possible feed elements.
  • Simple and easy to define channel and feed items
  • Implements appropriate namespaces for different versions.
  • Automatically converts date formats.
  • Generates UUID for ATOM feeds.
  • Enables usage of subtags and attributes. (example: image and encloser tags)
  • Completely Object oriented in PHP5 class structure.
  • Handles CDATA encoding for required tags.
  • Nearly same code for generating all kinds of feed

A minimum example

It’s a minimum example of using this class. I am generating a RSS 2.0 feed from retrieved data from a MySQL database. There are more examples in the download package for different versions.

<?php
  // This is a minimum example of using the Universal Feed Generator Class
  include("FeedWriter.php");
  
  //Creating an instance of FeedWriter class. 
  $TestFeed = new FeedWriter(RSS2);
  
  //Setting the channel elements
  //Use wrapper functions for common channel elements
  $TestFeed->setTitle('Testing & Checking the RSS writer class');
  $TestFeed->setLink('http://www.ajaxray.com/projects/rss');
  $TestFeed->setDescription('This is test of creating a RSS 2.0 feed Universal Feed Writer');
  
  //Image title and link must match with the 'title' and 'link' channel elements for valid RSS 2.0
  $TestFeed->setImage('Testing the RSS writer class','http://www.ajaxray.com/projects/rss','http://www.rightbrainsolution.com/images/logo.gif');
  
    //Retriving informations from database
    mysql_connect("server", "mysql_user", "mysql_password");
    mysql_select_db("my_database");

    $result = mysql_query("Your query here");

 
    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
        //Create an empty FeedItem
        $newItem = $TestFeed->createNewItem();
        
        //Add elements to the feed item    
        $newItem->setTitle($row['title']);
        $newItem->setLink($row['link']);
        $newItem->setDate($row['create_date']);
        $newItem->setDescription($row['description']);
        
        //Now add the feed item
        $TestFeed->addItem($newItem);
    }
  
  //OK. Everything is done. Now genarate the feed.
  $TestFeed->genarateFeed();
?>

Shhhh….a universal feed reader is on the way ;)

« Previous Entries