PHP Traits

Traits are a new phenomenon in languages which do not support multiple inheritance. PHP also not directly support multiple inheritance while interface can be used to simulate but due to their abstract behavior, they are less usefull when we need functionality from two or more parent class into child class and we want to through inheritance.

Here Traits are introduced. They do exactly what multiple inheritance do, And while take care of method collision.

See following example in PHP without trait.

class Phone
  public function ring()
  public function message()

class Computer
  public function email()
  public function surf()
  public function chat()

class Smartphone extends Phone


We can not inherit the functionality of Computer into Smartphone class here. As computer class is already defined and user in another world we can not convert it into interface. So we need to make Computer interface for Smartphone class need to reimplement which duplicate Computer class structure.

interface ComputerInterface
  public function email();
  public function surf();
  public function chat();

class SmartPhone extends Phone implements ComputerInterface
  public function email()
   // Copy implement here from computer class
  public function surf()
   // Copy implement here from computer class
  public function chat()
   // Copy implement here from computer class

As we see this is not efficient way some times. So we need to use design patterns to resolve this problem. But trait resolve this problem in language itself.

trait Phone
  public function ring()
  public function message()
  public function login()
  public function logout()

trait Computer
  public function email()
  public function surf()
  public function chat()
  public function login()
  public function logout()

class SmartPhone
  use Phone, Computer{
    Phone::login insteadof Computer;
    Computer::logout insteadof Phone;

$smart = new SmartPhone();

Here we also see how trait handle same method name collision. Their are more functionality similar to classes available in trait like inheritance and abstract methods.

See (

Programmer wannable attitude

Well, Grasshopper, or Unschooled Acolyte, or whatever your title of choice may be…

You did not hear this from me.

But most developers belong to the Church of Pain and we pride ourselves on our arcane talents, strange cryptic mumblings and most of all, the rewards due the High Priesthood to which we strive to belong.

Let me put it bluntly. Some of this very complicated logic is complicated because it’s very complicated. And pretty little tools would do both the complexity and us injustice, as high priests or priests-in-training of these magical codes.

One day we will embrace simple graphical tools. But only when we grow bored and decide to move on to higher pursuits of symbolic reasoning; then and not a moment before will we leave you to play in the heretofore unimaginable sandbox of graphical programming tools. Or maybe we’ll just design some special programs that can program on our behalf instead, and you can blurt out a few human-friendly (shiver) incantations, and watch them interpret and build your most likely imprecise instructions into most likely unworkable derivative codes. Or you can just take up LOGO like they told you to when you were but a school child in the… normal classes.

Does that answer your impertinent question?

Comes from

procedural MVC in php

Well I am reading some question on regarding procedural MVC in php. Then I am thinking why it should not be possible? After all MVC is about architecture, You can make good architecture also in procedural programming. You just need to design proper architecture. As I checkout on MVC Frameworks, their are some common terms like

  • Bootstrap script, which initializing system, core services, routers.
  • Controllers
  • Models
  • Views

Also library, helpers are available depend on project wise.

Now I am giving you some light on, How a MVC (very basic of course ) can be built on following style.


Project Root

config.php Sample Code :

define('MODEL_DIR', 'models');
define('VIEW_DIR', 'views');

$config = array (
    'default_module' => 'base',
    'default_action' => 'index',

lib/core.php Sample Code :

function safe($param) {
    return addslashes($param);

function render($file, $data)
    $layout_file = VIEW_DIR.'/layouts/layout.php';
    $content = ob_get_clean();

Bootstrap index.php Sample Code :

Let Request url is like /index.php?module=user&action=index

require_once('lib/core.php'); // For some core functions like render
//require_once('lib/db.php');   // For DB Abstraction [ Later Improvement ]

$module = isset($_REQUEST['module'])?safe($_REQUEST['module']):$config['default_module'];
$action = isset($_REQUEST['action'])?safe($_REQUEST['action']):$config['default_action'];

$controller_file = 'controllers/'.ucfirst($module).'Controller.php';
    trigger_error('Invalid Controller');
$function = strtolower($module).'_controller_'.$action;
    trigger_error('Invalid Controller Action');
call_user_func($function, $_REQUEST);

BaseController.php Sample Code :

function base_controller_index($request)
    render(VIEW_DIR.'/base/welcome.php', array());

UserController.php Sample Code :

function user_controller_index($request)
    $data = user_model_list($request);
    render(VIEW_DIR.'/user/index.php', $data);

function user_controller_add($request)

function user_controller_edit($request)

function user_controller_view($request)

Model User.php Sample Code :

function user_model_list($request)
    return array(
        array('name' => 'test', 'sname' => 'test1', 'city' => 'testc'),
        array('name' => 'abc', 'sname' => 'xyz', 'city' => 'mno'),

function user_model_add($request)

function user_model_edit($request)

function user_model_view($request)

Layout file views/layouts/layout.php Sample Code :

<link rel=’stylesheet’ href=’resources/css/style.css’ type=’text/css’ media=’all’ />
<div class=”content”>
<?php echo $content ?>

View views/base/welcome.php Sample Code :

<a href=”?module=user&action=index”>User Listing Page</a>

View views/user/index.php Sample Code :

<table class=”listing”>
<th>First Name</th>
<th>Last Name</th>
<?php foreach($data as $row) { ?>
<td><?php echo $row[‘name’] ?></td>
<td><?php echo $row[‘sname’] ?></td>
<td><?php echo $row[‘city’] ?></td>
<?php } ?>

Sample code could be found at

chat box effects by css

It is something strange for CSS effects article from a programmer. But yes today I am sitting on PC and check out some CSS effects after some explore I get the cute box can be used for a chat box.

These is generated after some css3 special effects like shadow, radius, transform. The css can be applied like that.

    .box {
        width: 300px;
        min-height: 50;
        border-radius: 5px;
        box-shadow: 3px 3px 5px 6px #ccc;
        padding: 15px;
        margin: 10px;
        font-family: arial;
        font-size: 13px;
        transform: skew(-10deg);
        -webkit-transform: skew(-10deg);


Screenshot for resulted box is 


While all effects work on FF20 on without using -moz prefix, While for strange reason Chrome 25 still need -webkit prefix to apply transform effects.

You can check the demo from

Some Quotes

I think he knows what Rome is. Rome is the mob. Conjure magic for them and they’ll be distracted. Take away their freedom and still they’ll roar. The beating heart of Rome is not the marble of the senate, it’s the sand of the coliseum. He’ll bring them death – and they will love him for it. (From Gladiator Movie, Ref Mob mentality)

Working with subversion – II

In previous article, I discuss some basic functions of svn. Now i will discuss some more handful features for svn.

But first one disclaimer I will only show some basic example for svn commands. They are very powerful and can be used with variety of parameter to achieve required results.

First sometimes we need to know about our svn setup. So svn info comes as handy here.

$ svn info
Repository Root:
Repository UUID: 3aaa9e22-3660-1222-1111-ccca444822
Revision: 10
Node Kind: directory
Schedule: normal
Last Changed Author: User1
Last Changed Rev: 10
Last Changed Date: 2013-03-13 01:23:12 +0530 (Wed, 13 Mar 2013)

As you see it gives information like SVN url total revision last commited revision info etc.
Some times we will need to analyze the changes log. For that svn log command is very handful.
Syntax : svn log <File Path>

$ svn log test.php
r2 | user2 | 2013-03-13 01:23:12 +0530 (Wed, 13 Mar 2013) | 2 lines
some changes
r1 | user1 | 2013-03-13 01:14:14 +0530 (Wed, 13 Mar 2013) | 1 line
First code commit

This is helpful to check which user commited which version. You can also track down the previous version file contents through svn cat command
Ex. for check test.php for version 123

Syntax : svn cat -r<revision> <File Path>


$ svn cat -r123 test.php

For save into file to analyze, use bash stdout like that

$ svn cat -r123 test.php > test-prev.php

One more command is very much used for track down changes between versions and that is svn  diff

Syntax : svn diff <File Path>


$ svn diff test.php

Above command returns the difference between latest commited version and uncommited changes for test.php. You also can check difference from any particular revision by pass revision.

Syntax : svn diff -r<revision> <File Path>

Example for Changes in test.php after version 4.

$ svn diff -r4 test.php

Their are times when you need structure without svn footprints (folders/files related to svn ) Example to upload somewhere. You need svn export command.

Syntax : svn export <Folder Path to export structure >


$ svn export /home/user/backups/

It will create project123 folder into /home/user/backups/. Remember it will create folder, you should not create folder at that path with same name.

I hope these cheat sheet for svn is usable for readers

Working with subversion – I

Their are many version control software available in market. Subversion/svn can be said market leader atleast for centralized systems. Today I can discuss some most used svn client commands for better project handling.

First you need to install subversion, So fire apt-get command on your shell window.

$ apt-get install subversion
Now subversion is installed on your system.

First command you need is cloning the repository into your local system. So you need to take svn checkout for that repository.

$ svn checkout

you can also use short word co instead of checkout.

After checkout we need some work. So let create a file test.php and put some code into it. Now if we analyze through following command we see output like this

$ svn status
? test.php

? mark says that it is still not part of your svn repository. You need to add it by
$ svn add test.php

You can use bash expression like test.* or folder/*php or similar to add multiple files/folder into svn.

now if you use svn status, output is different then previous

$ svn status
A test.php

This changes is local till now, And we need to commit the changes on server.

$ svn commit test.php -m 'ADD MESSAGE'

If you skip message part through line a default shell editor (like nano/vim) opened to fill message, You entered and save/exit through editor Then file is commited as previous command

$ svn commit test.php

You can also remove the any file in svn by using svn delete command. It works on local copy like svn add does and requires svn commit after it to done actually on server.

$ svn delete test.php
$ svn commit test.php -m 'DELETE MESSAGE'

Now Let if you added a file, remove a file or make changes in any of file, But not commited that file on server. You can revert your changes using revert command.

$ svn revert test.php

Afte verify on svn status you will found that,
This command removed the A flag and Add ? on previously svn added file
This command removed the D flag on previously svn deleted file
This command removed the U flag on previously updated file

NOTE : In any case commited changes can not be reverted through revert command.

For take latest changes from server, we need update command. This is little tricky as It will involve merge your changes with updates comes from server. And most challenging part of svn is to take care of it.

$ svn update
A test.php
D test1.php
U test2.php
G test3.php
C test4.php

These are most common updates return from server.

  • A denotes any newly added file on server added to your local structure.
  • D denotes any any file is deleted on your local structure as that file is rmeoved on svn serve too .
  • U denotes simple update on any file when you have not any local changes.
  • G denotes simple update on any file when you have any local changes but not on same line.
  • C denotes simple update on any file when you have any local changes on same line.

There are chances when update comes on file where you have any local changes on same line. Then their would be a prompt for conflict management with options p – postpone, df – diff, mc – mine-conflict, tc – their conflict. More

  • df option show the diff of both version.
  • mc option merge updations with the case that in case of same line conflict, local changes will be taken.
  • tc option merge updations with the case that in case of same line conflict, remote changes will be taken.
  • p option merge both version with conflict lines/part will be shown as <<< >>> block. That need to resolved first to commit. It also create some more files like test.php.mine, test.php.r101, test.php.r104. Where test.php.mine is local file before potpone merging. test.php.r104 or test.php.r<remote version> file having remote changes. test.php.r101 or test.php.r<remote previous version> file having previous remote commited version  changes.

After using postpone options and creating required changes, You need to resove conflict by

$ svn resolve test.php

There are two options available but not shown in  prompt.

  • mf option discard remote file changes and take local file as verify version.
  • tf option discard local file changes file and take remote file as verify version.

NOTE 1 : You need to commit changes in case of svn update file status G and C.
NOTE 2 : You may need to enter svn username/password in case of svn checkout/update/commit

That all for this article, We will discuss some more interesting features of svn in next article.

Basic Ejabberd install/setup on ubuntu (External Script Authentication)

In first article, I discussed the installation and normal chat with users registered internally. Now i am going to discuss the external authentication through a php script.

If you want to authenticate users via your database. their are two alternatives.
1. Using odbc, It have one restriction as its internal database have and that is password must be stored plain. (Latest version may not have this restriction.)
2. Using external authentication script. In this way you can authenticate user via a custom script. Here one good php script can be found there. Now download an extract in some location of your system (not necesarily on apache document root as it will working as cli script ).

Now first create a php script in same folder. I name it auth.php. This file should have similar code suggested at github page. I am updating it using some real query.

require 'ejabberd_external_auth.php';
class Auth extends EjabberdExternalAuth {
    protected function authenticate($user, $server, $password) {
        $stmt = $this->db()->prepare("SELECT user_id FROM user WHERE username = ? AND password = ? ");
        $stmt->execute(array($user, password));
        if($stmt->rowCount() >= 0 )
            return true;
            return false;

    protected function exists($user, $server) {
        $stmt = $this->db()->prepare("SELECT user_id FROM user WHERE username = ? ");
        if($stmt->rowCount() >= 0 )
            return true;
            return false;
$pdo = new PDO('mysql:dbname=testdb;host=', 'user', 'password');
new Auth($pdo, 'auth.log');

I skipped $server argument in query check as If you need only users for one chat server. If you need to handle multiple servers then you may need to change code to reflect server too in query.

Now comment internal auth_method by

%%{auth_method, internal}.

And uncomment, change the line

{auth_method, external}.
{extauth_program, "/path/to/auth.php"}.

gave executing permission to auth.php by chmod 0755 auth.php.

NOTE – As this script executed by ejabberd user created at time of ejabberd installation. So this script need execute permission for ejabberd. You may add ejabberd to your user’s group and gave group to execute permission or gave other to execute permission. In both case it is advisable to check execute file after login through other user.

Add chat users in your user table. You will also need admin user to add into your DB with same password to run admin console.

Now restart ejabberd. and verify by adding user at you jabber client. if it going failed. Then verify log file var/log/ejabberd.log. If file have error to not connecting. check php script again for any error.

Ejabberd default enabled MUC (multi user chat or several other modules ), So you can verify/use also this functionality too.

That’s all for this article, In next article I will discuss message logging.

Basic Ejabberd install/setup on ubuntu

In social web appliactions, Jabber chat comes as popular choice for implementing self chat gateway/servers. While there are several chat server are available in market like ejabberd, jabberd2, openfire.
Ejabberd is chat server built in erlang. It provide various recommended features by core/plugins.

Now I am going to give some information for setup ejabberd chat server onto Ubuntu 12.04.

First you need to install ejabberd package. There are two ways.
1. Through ubunty repository. While this option require less work, But you may not get latest package for ejabberd.
2. Download ejabberd package and compile it. This option require more work, But you can get latest package havig more features.

We going through First easy approach.
Here we install ejabberd via

sudo apt-get install ejabberd ejabberd-tools

After installation completion, we will doing some intial setup and configuration.
We need to configure our first chat domain. Here we have config file names ejabberd.cfg at /etc/ejabberd folder.
Open it into your editor, and go for line look like below.

{hosts, ["localhost"]}.

Then change it to add your domain/ip-address as Chat server host.

{hosts, ["localhost",""]}.

Also setup your admin user via change config.

{acl, admin, {user, "", "localhost"}}.


{acl, admin, {user, "administrator", "localhost"}}.

Where administrator is admin-name chosen by you. (Ofcourse you can choose any name as admin.)

After save you should also register your admin via command run on shell.

ejabberdctl register administrator localhost password

Now you should restart ejabberd by executing commands

sudo /etc/init.d/ejabberd restart

Open Admin Console via the url – http;//localhost:5280/admin. It ask you the enter admin credentials. enter administrator name and its password, setup via ejabberctl.
Here you can add users via going to virtual hosts -> localhost[] ->  Users.

After register users at here you can start chat by your jabber client example pidgin or spark.

Ejabberd default using it internal database called mnesia to store all kind of information like users, room, logs etc.

In second article of series, I will discuss the external authentication and logging.

Assign role to user in doctrine

From start of days of symfony sfauth plugin play a special role in making developer’s life easy. It give structured way to assign roles and permissions to user.
So at the time of creation of user add/edit forms you can see the groups (roles) and permissions to choose. Also permissions can also direct work for whole group.
But if we need to set permissons/roles to user without using forms then how it can be implemented?
Well yesterday i am searching any workaround for this.
Normally we can use code like that
$sf_user = new sfGuardUser();
But i need to set groups against user. Here are a problem, group have many to many relationship with user. Si how i can set the group using similiar code. First i tried following combinations but no one seems to work. Some gave errors some not.
Here $group is not a normal variable but a doctrine collection of group.
$sf_user->Groups = $group;

As user can have multiple groups so setting group also reflect the same way.
$sf_user->Groups[] = $group;
Here we can see we are not assigning but adding a group against a user. So above example works.