Register Doctrine2 type mapping with Symfony2

Well, few of us may have encountered such error while using Doctrine like “Unknown database type enum requested, Doctrine\DBAL\Platforms\MySqlPlatform may not support it.” or in my case I was trying to use “enum” type with doctrine.

So, here is the app/config.yml hack at mapping_types:

# Doctrine Configuration
        driver:   %database_driver%
        host:     %database_host%
        port:     %database_port%
        dbname:   %database_name%
        user:     %database_user%
        password: %database_password%
        charset:  UTF8

          enum: string
          set: string
          varbinary: string
          tinyblob: text
        auto_generate_proxy_classes: %kernel.debug%
        auto_mapping: true

Setting your PHP development environment in Ubuntu

Instead of installing each item separately we will go with installing LAMP server in a package in Ubuntu that is fairly simple along with a single terminal command:

sudo apt-get install lamp-server^

The apt-get command is a powerful command-line tool used to work with Ubuntu’s Advanced Packaging Tool (APT) performing such functions as installation of new software packages, upgrade of existing software packages, updating of the package list index, and even upgrading the entire Ubuntu system.

sudo used to invoke the current user with the power of super user and a caret ‘^’ symbol placed after package name to indicate performing as tasks together.

The LAMP package will start installing immediately with above command including latest PHP5, Apache 2, MySQL and PHP5-MySQL. By default apache2 and MySQL installed as service and your document root will be at /var/www/

An index.html file shall be there.

Both Apache and MySQL should be running. However, you may start apache by using service start command as

sudo service apache2 start

and stop apache by using:

sudo service apache2 stop

Checking the LAMP installation:

Point your browser to http://localhost/ you will see the default apache2 landing page which means your webserver apache2 is running. Still you can check those service statuses as below:

sudo service apache2 status

you will be shown

Apache is running. Process #

Again to check MySQL status, simple run the command

sudo service mysql status

you will be shown

mysql start/running. Process #

to check the PHP installation simple create a file named test.php, in /var/www/ with the below line:

<?php phpinfo(); ?>

Now point your browser with http://localhost/test.php and you will see the installed PHP and components configuration details.

Installing PhpMyAdmin:

To maintain MySQL database functionality using web based interface we may use phpMyAdmin.

sudo apt-get install phpmyadmin

phpMyAdmin will be installed with the above command and during installation you will receive a blue window asking which server you want to use i.e. apache2, lighttpd ;  choose apache2 and click ok to continue with the installation. After installation point your browser with http://localhost/phpmyadmin/ and you will be viewing phpMyAdmin landing page.

If you receive 404 error at http://localhost/phpmyadmin/ then you need to setup phpMyAdmin under apache manually by modifying /etc/apache2/apache2.conf using gedit

sudo gedit  /etc/apache2/apache2.conf

gedit will open the file in graphical mode and add the below line at bottom inside apache2.conf

Include /etc/phpmyadmin/apache.conf

Now restart apache server to make the changes effective.

sudo service apache2 restart

Now refresh your browser and you will have phpMyAdmin login screen.

PhpXperts Seminar 2011 – follow up

17th December 2011, on tech premises at the heart of Dhaka, the largest tech seminar took place once again featuring latest web trends and interesting PHP sessions brought by the experts from the industry. In this 5th annual program of phpXperts, more than 500 developers, open source enthusiasts, journalists, students, geeks joined the daylong event to inhabit the tech gathering which finally became huge success and significant in the local PHP community.

This long awaited annual program included with a new addition of short sessions of 6 minutes each along with regular sessions with speakers and the sponsors presented their companies or projects within the event frame. The pretty item in the seminar was the quiz session after each two speaking and winners were awarded with many exciting gadgets.

Basically openness & friendliness of phpXperts community became the icon of tech community of the country, more auspicious developers have been stimulated from the phpXperts. This enormous tech group feeds heavy input to local web industry and the web generation of Bangladesh.

Hasin Hayder, the man behind the scene, doing the hard work as founder-moderator of the group and the mentor to local PHP community.

Seminar references are as below:


Sessions with Speakers

Lets have some fun with – Twilio & OpenTok APIMizanur Rahman

Get Excited! Enterprise Search Solutions at your FingerTipsMurshed Ahmmad Khan

Dependency Injection, Reinventing how you manage PHP classesRifat Nabi

Setting up Amazon EC2 Servers: Make Your Server Elastic!Tahsin Hasan

Continuous feature integration in large projectsNHM Tanveer Hasan Khan & Nafi ul karim

MongoDB, a document store that won’t let you down!Nurul Ferdous

Getting Up and running with Zend FrameworkMd. Shoriful Islam Ronju & Saidur Rahman Bijon

A Brief Intro to the Symfony Application Framework v2.xLoban Amaan Rahman


Taking Advantage of Client Side / JavaScript Templates in Rich Internet Applications. – M. Mahbubur Rahman

Hybrid authentication and talking to social networksRayhan Chowdhury

Supervisor, Gearman and PHP – Job management with sanity!Abu Ashraf Masnun

Mystery of cryptography, ciphers and the dark side of the moonHasin Hayder & M A Hossain Tonu


6 minutes of Fame

Smelling Your CodeRaju Mazumder

WordPress plugin / theme development best practicesTareq Hasan

Flying on the cloudImran Hossain Shaon

Rapid facebook application development using LightBulb – Md. Alamgir Hossain Rinku

ZCE – Inside OutShehzad Noor Taus

RESTful Web ServicesMd. Eftakhairul Islam Rain

Download all the presentation slides:

Seminar booklet:

Cover Design of the booklet of phpXperts

Photo Albums:

Seminar follow up in Bengali:

Cheers 🙂

Bootstrap-ing in Zend Framework


Bootstrap.php inside your application directory runs before your application loads in order to process auto loading of resources. resource auto loading can be performed in two ways using either Bootstrap.php or application.ini for an application.

Bootstrap methods used as initialize-r should be of protected and begin with _init.

As an example, you want to initialize language translation resource, create a method like _initTranslation() as below:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
      protected function _initTranslation(){
      //translation enabling codes here

bootstrap methods are named according to functionality i.e. _initLayout(), _initViewHelpers(), _initRoutes() etc.

here are two examples of bootstrap methods:

jQuery, jQuery ui/css enabler

 * enable jquery, jqueryui, css
protected function _initJquery() {
  $view = $this->getResource('view');

  //add jquery view helper path
  $view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");
  //jquery lib includes here

in the above code we just enabled to make available jQuery, ui to our application.

doc type, header

 * declare header, doc type etc.
protected function _initDoctype() {
   $view = $this->getResource('view');

   //doc type
   $view->headMeta()->appendHttpEquiv('Content-type', 'text/html;charset=utf-8')
        ->appendName('description', 'test description');

in the above method we declared doc type, charset etc. for our html documents belongs to the application.

Using Multiple Layouts in Zend Framework

Followed by my earlier post >>

Besides using default layout you can use multiple layouts or can switch between layouts. All you need to do is just pick the layout object and set the desired layout name.

Here is a scenario:

Say you have 2 layouts at application/layouts/scripts/ i.e. layout.phtml and layout1.phtml

As layout.phtml is your default layout and you need to use layout1 in some cases. To do that we need to pick the layout object as mentioned earlier, there are several ways.

Access a layout object:

At view scripts:

<?php $layout = $this->layout(); ?>

At action controller:

$layout = $this->_helper->layout();

Static method elsewhere:

$layout = Zend_Layout::getMvcInstance();

At bootstrap:

$layout = $bootstrap->getResource('Layout');

Set the desired layout (the layout will work within defined scope):


i.e. If you set the layout at any action controller then the layout will be viewed for that particular action.

For more reading

Enabling Layout in Zend Framework

See Category:Go images for sourcecode and usag...
Image via Wikipedia

To maintain a consistent look and feel through out your website, Zend_Layout provides layout facility by which you can create single or multiple document structures as like as templates.

Enabling Zend_Layout means informing bootstrap to use Layout resource. You can enable layout with the help of zf cli tools from terminal as:

$ zf enable layout

Layout has been enabled, and a default layout created at application/layouts/scripts/layout.phtml. A layout entry has been added to the application config file.

With the above command you will have following things ready:

–       application/configs/application.ini is updated; contains following line at your production section

resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"

–       A layout file created at /application/layouts/scripts/layout.phtml

Also you need to initialize the View resource; add the following line to your have application/configs/application.ini

; Add to [production] section:

resources.view[] =

Now to run view resource we will add just a little code at bootstrap:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {

protected function _initView(){


$view = $this->getResource('view');

$view->doctype('XHTML1_STRICT'); //can set the doc type here



Now  Zend_Layout is ready to go; may modify the layout or add some styles. Just don’t forget to echo your content i.e. $this->layout()->content  at your layout body to display your content or view html segments:

<!-- application/layouts/scripts/layout.phtml -->

<?php echo $this->doctype() ?>

<html xmlns="">


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>my title</title>



<?php echo $this->layout()->content ?>



It’s a go!

if you need to use multiple layouts, you may read my next post on multiple layout usage

Using jQuery and jQuery ui with Zend Framework

talkin' jquery ui
Image by "Cowboy" Ben Alman via Flickr


For those jQuery fanatics like me wants to jQuery enabled in their Zend framework application, zf provides view and form helpers through it ‘extras’ library, also it is handy to enable.

At Bootstrap class add the following initialization method like below:

* init jquery view helper, enable jquery, jqueryui, jquery ui css

protected function _initJquery() {

$view = $this->getResource('view'); //get the view object

//add the jquery view helper path into your project
$view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");

//jquery lib includes here (default loads from google CDN)
$view->jQuery()->enable()//enable jquery ; ->setCdnSsl(true) if need to load from ssl location
     ->setVersion('1.5')//jQuery version, automatically 1.5 = 1.5.latest
     ->setUiVersion('1.8')//jQuery UI version, automatically 1.8 = 1.8.latest
     ->addStylesheet('')//add the css
     ->uiEnable();//enable ui


At the <head> section of your document or at layout.html, to enable jQuery at your each pages just echo like below:


echo $this->jQuery();


So you will have jQuery and jQuery ui files added into your document section like as always:

<link rel="stylesheet" href="" type="text/css" media="screen" />

<script type="text/javascript" src=""></script>

<script type="text/javascript" src=""></script>


N.B: in order to use ZendX library under extras/library/ZendX, the ZendX directory path should be in your php include_path or alternatively can SymLink the ZendX directory under your /application/library/


Setting up your development with Zend Framework


In general, Zend Framework is an object oriented web application framework for PHP 5. Zend Framework is often called a ‘component library’, because it has many loosely coupled components that you can use more or less independently. It also provides advanced Model-View-Controller implementation.

In order to setup the development environment with Zend framework we will go through the below procedures:

1. Download and Install

Download the latest version of Zend Framework and extract the contents into your desired location or can have a checkout copy from the Subversion repository.

Some extensions may be required such as GD, iconv etc. (Zend Framework will notify you if any required while your application runs, so don’t worry about that now). If you are much interested about those extensions required can read more here

2. Creating your project using zf Command Line Tool

Before creating your project you need to know the use of zf command line tool. Here we go

In your Zend Framework installation is a bin/ subdirectory

for *nix = and for Windows = zf.bat . Track the absolute path to that script.

On Unix-like systems, you may want to use your shell’s alias functionality:

$ alias zf =path/to/ZendFramework/bin/

If you have problems setting up the zf command-line tool, please refer to the manual.

Now from the terminal or command prompt, execute following command

$ zf create project projectname projectpath

This will create your basic project director structure i.e. directory for controllers, models, views etc.

3. Add Zend Framework to your include_path

Now either choose a) or b) to make available the zf components to your project. I like b)

a)     Add Zend Framework installation path to your php include_path

b)    Symlinking path/to/ZendFramework/library/Zend inside your path/to/projectname/library/ with this command

$ ln -s path/to/ZendFramework/library/Zend path/to/projectname/library/

If you are planning to use jQuery later you may Symlink the ZendX directory found under extras/library inside your project library as:

$ ln -s path/to/ZendFramework/extras/library/ZendX path/to/projectname/library/

So you will have alias to above Zend directories inside your project library sub directory. All you are doing is just making Zend Framework available to your project. You may follow identical practice for multiple zf projects.

4. Bootstrap-ing

Bootstrap class defines what resources and components to initialize. Zend framework runs the Bootstrap.php(can be found just under each application dir) file before loading any modules or applications. So we can put all sort of initialization tasks there.

As an example, we put doc type initializer inside the class as below:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
protected function _initDoctype() {
$view = $this->getResource('view');
//doc type
$view->doctype('XHTML1_STRICT'); // doc type to xhtml strict
$view->headMeta()->appendHttpEquiv('Content-type', 'text/html;charset=utf-8') //utf-8 enabled
->appendName('description', 'my zf project');

5. Configuration

The default configuration file can be found under /application/configs/application.ini

It looks like below:

; application/configs/application.ini
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
[staging : production]
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1

You can update the file as per your requirements. As for an example, lets add database connection credential at [production] section, so the zf connects the database automatically using the config provided as below

;DB connection credentials
resources.db.adapter = "PDO_MYSQL" //pdo adpter for mysql = "localhost"
resources.db.params.username = "root"
resources.db.params.password = "root"
resources.db.params.dbname = "test_database"

So you will have your database connected with your zf project.

6. Creating action controllers, views as well

Run the following command using zf cli tool to create controller each time:

$ zf create controller name

Now you will have a controller class created inside your controller directory and a view subdirectory (same name) created with default index view file named index.phtml inside your views directory.

To create action method under that controller class simple run the command:

$zf create action name controllername

By this you will have the view file with the same name created automatically for that action method too.

You may follow up the changes appearing each time at that controller class by opening it.

Up to now you suppose to be able to browse your project by visiting url like http://localhost/projectname/public/

7. Creating views (optional)

Run the following command using zf cli tool to create view file explicitly for a controller/action each time:

$ zf create view controllername actionname

8. Creating virtual host (optional)

Assuming you are using Apache web server, at your working httpd.conf define a vhost by adding the below snippet (replace myzfproject with your project name, also the path):

<VirtualHost *:80>
DocumentRoot /path/to/ myzfproject /public
SetEnv APPLICATION_ENV "development"
<Directory /path/to/ myzfproject /public>
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all

Using SetEnv APPLICATION_ENV “development” line you are setting the environment variable for zf application, resulting the zf will pick configurations from [development] section from application.ini. Drop this line for having “production” config by default.

Add an entry at the end of your hosts file regarding the value in ServerName :

Location of hosts file:

On *nix: /etc/hosts On Windows: C:\WINDOWS\system32\drivers\etc\hosts

Restart your web server and you are likely to drive.

Visit for more information

Both Zend Developer Zone and the Wiki have links to ZF tutorials and articles. Consider subscribing to the fw-general mailing list but especially the SVN commit list

Cache PHP output for high traffic websites. PEAR: Cache_Lite


Now days the WebPages are outcome of heavy script processing in order to provide more dynamicity to page visitors. The utility of server side scripting is to adopt more engineering on web. When the page gets more visitors or becomes more popular, you have to ensure that, that traffic doesn’t stack or queued in front of your freaky web server. All you have to do is to serve them with your page and ofcourse serve it faster. Again server side scripting requires processing and compiling.

In order to serve pages faster, to make light use of server side processing and compiling and to survive within heavy traffic, caching dynamic script output is needed.

The Need For Speed…

Every time a request hits your web server, PHP has to do a lot of processing, all of your codes have to be compiled and executed for a single traffic hit every time. Interesting thing will be if the outcomes of all these processing is identical for each visitors. Say, processing happens every time for visitor 24500 and 24501 while the outputs are so same. Argh!!

What would be if we save the flat HTML generated for visitor 24500 and serve that to 24501 as well??? That will be awesome 😀 coz this leads to less processing and faster page handover. This da mechanism we are talking about, yeah! Cache PHP output 😀

Well we can write such optimization system but there is a smart package in PEAR called Cache_Lite that can do this job for us. Let’s check out why Cache_Lite:

  • It saves time of writing new caching codes 😀
  • It’s optimized for high traffic websites
  • Robust, easy to implement
  • Have time to time documentation
  • Bunch of cool features. 🙂


The Cache_Lite class comes courtesy of PEAR, the “PHP Extension and Application Repository” ( In case you didn’t know, PEAR is an online repository of free PHP software, including classes and modules for everything from data archiving to XML parsing. When you install PHP, a whole bunch of PEAR modules get installed as well; the Cache_Lite class is one of them.

In case not installed then…

It is just like coding hello world!! 😀

On ubuntu:

sudo aptitude -y update
sudo aptitude install php-pear

Now that we have PEAR, i would use it to install the Cache_Lite extension

sudo pear install Cache_Lite

Perfect! 😀

Checking whether installed/ checking PEAR verson:

Both pear and pecl tools should be available everywhere on command line. For that to work, pear’s binary (bin) directory should be in your PATH variable.

To verify it works, simply type pear. A list of commands should be shown:

$ pear
build                  Build an Extension From C Source
bundle                 Unpacks a Pecl Package
channel-add            Add a Channel

You should further test that PEAR is up to date:

$ pear version
PEAR Version: 1.7.2
PHP Version: 5.2.6RC4-pl0-gentoo
Zend Engine Version: 2.2.0
Running on: Linux ...

More installation queries here:



// Include the package
require_once('Cache/Lite.php'); // make sure cache_lite script path

// Set a id for this cache
$id = '123';

// Set a few options
$options = array(
    'cacheDir' => '/tmp/',
    'lifeTime' => 3600

// Create a Cache_Lite object
$Cache_Lite = new Cache_Lite($options);

// Test if thereis a valide cache for this id
if ($data = $Cache_Lite->get($id)) {

    // Cache hit !
    // Content is in $data
    // (...)

} else { // No valid cache found (you have to make the page)

    // Cache miss !
    // Put in $data datas to put in cache
    // (...)




More clearly…

require_once "Cache/Lite.php";

$options = array(
    'cacheDir' => '/tmp/',
    'lifeTime' => 7200,
    'pearErrorMode' => CACHE_LITE_ERROR_DIE
$cache = new Cache_Lite($options);

if ($data = $cache->get('id_of_the_page')) {

    // Cache hit !
    // Content is in $data
    echo $data;

} else {

    // No valid cache found (you have to make and save the page)
    $data = '<html><head><title>test</title></head><body><p>this is a test</p></body></html>';
    echo $data;



If you wish use a cache per block and not a global cache, take as example the following script:


$options = array(
    'cacheDir' => '/tmp/',
    'lifeTime' => 3600

// Create a Cache_Lite object
$Cache_Lite = new Cache_Lite($options);

if ($data = $Cache_Lite->get('block1')) {
} else {
    $data = 'Data of the block 1';

echo('<br><br>Non cached line !<br><br>');

if ($data = $Cache_Lite->get('block2')) {
} else {
    $data = 'Data of the block 2';


Little bit implementation:

The key point is Cache_Lite maintains a unique identifier for every page. Cache_Lite will check for that identifier used before. If so, it will retrieve the stored HTML from disk (can use RAM as turbo charged storage i.e. mount tmpfs in RAM memory) and echo it right away. If not, we:

  • turn on output buffereing so we can catch all following content
  • we include the original PHP code
  • catch the output buffer, and let Cache_Lite store it on disk for the next time.
  • and then echo it



/* Include the class */
require_once 'Cache/Lite.php';

/* Set a key for this cache item */
$id = 'newsitem1';

/* Set a few options */
$options = array(
    'cacheDir' => '/var/www/',
    'lifeTime' => 3600

/* Create a Cache_Lite object */
$Cache_Lite = new Cache_Lite($options);

/* Test if there is a valid cache-entry for this key */
if ($data = $Cache_Lite->get($id)) {
    /* Cache hit! We've got the cached content stored in $data! */
} else {
    /* Cache miss! Use ob_start to catch all the output that comes next*/

    /* The original content, which is now saved in the output buffer */
    include "requiredPhpFile.php";

    /* We've got fresh content stored in $data! */
    $data = ob_get_contents();

    /* Let's store our fresh content, so next
     * time we won't have to generate it! */
    $Cache_Lite->save($data, $id);
echo $data;


A Special case…

Say a case, is to automatically purge an article’s cache when a comment has been placed. You could for example place this before Cache_Lite checks if it’s got a cache page for a specific $id:

if(isset($_POST["add_comment"]) && $_POST["add_comment"]){


Docs for Cahe_Lite here:

Tricky concepts in PHP

Include Vs Require

include() and require() are slightly different.Basically, include is conditional and require is not.

This would include ‘somefile’ if $something is true:




This would include ‘somefile’ unconditionally




This would have VERY strange effects if somefile looked like:

} echo “Ha!I’m here regardless of something: $something<br>n”;

if (false) {

Another interesting example is to consider what will happen if you use include() or require() inside a loop.

$i = 1;

while ($i < 3) {


$i ;


Using require() as above will cause the same file to be used every single iteration.Clearly this is not the intention since the file name should be changing in each iteration of the loop.We need to use include() as below.Include() will be evaluated at each iteration of the loop including somefile.0, somefile.1, etc as expected.

$i = 1;

while ($i < 3) {


$i ;


The only interesting question that remains is what file will be required above.It turns out that PHP uses the value of $i when it reads the require() statement for the first time.So, the require() loop above will include something.1 two times.The include() loop includes something.1 and something.2.

Echo Vs Print

There is a difference between the two, but speed-wise it should be irrelevant which one you use.print() behaves like a function in that you can do:

$ret = print “Hello World”;

and $ret will be 1.

That means that print can be used as part of a more complex expression where echo cannot.print is also part of the precedence table which it needs to be if it is to be used within a complex expression.It is just about at the bottom of the precedence list though.Only “,” AND, OR and XOR are lower.

echo is marginally faster since it doesn’t set a return value if you really want to get down to the nitty gritty.

If the grammar is:

echo expression [, expression[, expression] … ]


echo ( expression, expression )

is not valid.( expression ) reduces to just an expression so this would be valid:

echo (“howdy”),(“partner”);

but you would simply write this as:

echo “howdy”,”partner”;

if you wanted to use two expressions.Putting the brackets in there serves no purpose since there is no operator precedence issue with a single expression like that.