The observer pattern in PHP

In my last 2 post i tried to give an idea about singleton and factory design pattern. Toady i would like to share the idea regarding “The observer pattern”. It gives you another way to avoid tight coupling between components. This pattern is simple: One object makes itself observable by adding a method that allows another object, the observer, to register itself. When the observable object changes, it sends a message to the registered observers. What those observers do with that information isn’t relevant or important to the observable object. The result is a way for objects to talk with each other without necessarily understanding why.

A simple example is a list of users in a system. The following code shows a user list that sends out a message when users are added. This list is watched by a logging observer that puts out a message when a user is added.

Continue reading

Tagged , , ,

Design Pattern in php – Factory Method

In my last post i tried to provide an idea about singleton design pattern with an example in php. Today i am going to write about something on Factory Method design pattern and how to create a factory class according to this pattern in php.

For example, we are creating an interface for creating objects, but let the subclasses decide which class to use. This is just like a real life factory. It creates the type of product what we want, based on the order we put in. What ever is inside that factory decides on which tools to use to get the job done.Imagine we have a factory that makes all kinds of note books. For this instance we’ll be creating a Dell, Toshiba, or a Apple MacBook Air. If we place an order saying we want a Apple MacBook Air, then we expect a Apple MacBook Air is going to come out of that factory. We don’t need to know how it’s made, or how it’s different from others, just that we get what we asked for. That’s the beauty of the Factory Method design pattern. It encapsulates how things are made, so we don’t need to know all the details. This is huge, because if a note book changes the way it was made, we as the developer don’t have to worry about it. The note book’s class will change, but how we access that class remains unchanged. This is abstraction at it’s best. Here is an example in PHP.

Continue reading

Tagged , , ,

How to use singleton design pattern in your php code

The Singleton Pattern is one of the Gang of Four Patterns. This particular pattern provides a method for limiting the number of instances of an object to just one. It’s an easy pattern to grasp once you get past the strange syntax used. Consider the following class:
class Database
{
public function __construct() { ... }
public function connect() { ... }
public function query() { ... }
...
}

This class creates a connection to database. Any time we need a connection we create an instance of the class, such as:
$pDatabase = new Database();
$aResult = $pDatabase->query('...');

Lets say we use the above method many times during a script’s lifetime, each time we create an instance we’re creating a new Database object and thus using more memory. Sometimes you may intentionally want to have multiple instances of a class but in this case we don’t.

The Singleton method is a solution to this common problem. To make the Database class a Singleton we first need to add a new property to the class, lets say it $m_pInstance:
class Database
{
// Store the single instance of Database
private static $m_pInstance;...
}

As the comment states, this property will be used to store the single instance of the Database class. You should also note that this property must be static.

Next we need to change the constructor’s scope to private. This is one of the strange syntaxes that usually confuse people.
class Database
{
// Store the single instance of Database
private static $m_pInstance;
private function __construct() { ... }
}

By making the constructor private we have prohibited objects of the class from being instantiated from outside the class. So for example the following no longer works outside the class:
$pDatabase = new Database();

We now need to add a method for creating and returning our Singleton. Add the following method to the Database class: Continue reading

Tagged , ,

Calling Web Services in Android using HttpClient

public class RestClient {

    private ArrayList <NameValuePair> params;
    private ArrayList <NameValuePair> headers;

    private String url;

    private int responseCode;
    private String message;

    private String response;

    public String getResponse() {
        return response;
    }

    public String getErrorMessage() {
        return message;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public RestClient(String url)
    {
        this.url = url;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
    }

    public void AddParam(String name, String value)
    {
        params.add(new BasicNameValuePair(name, value));
    }

    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }
    public void Execute(RequestMethod method) throws Exception
    {
        switch(method) {
            case GET:
            {
                //add parameters
                String combinedParams = "";
                if(!params.isEmpty()){
                    combinedParams += "?";
                    for(NameValuePair p : params)
                    {
                        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),”UTF-8″);
                        if(combinedParams.length() > 1)
                        {
                            combinedParams  +=  "&" + paramString;
                        }
                        else
                        {
                            combinedParams += paramString;
                        }
                    }
                }

                HttpGet request = new HttpGet(url + combinedParams);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                executeRequest(request, url);
                break;
            }

Continue reading

Tagged , , , ,

7 Habits of Highly Effective People – Interesting

Last Saturday i attended an Interesting training of my office which describes the human character and how to improve & Organize our life. It describes the seven habits of effective people which was like this,

Habit 1:  Be Proactive

Change starts from within, and highly effective people make the decision to improve their lives through the things that they can influence rather than by simply reacting to external forces.


Habit 2:  Begin with the End in Mind

Develop a principle-centered personal mission statement. Extend the mission statement into long-term goals based on personal principles.


Habit 3:  Put First Things First

Spend time doing what fits into your personal mission, observing the proper balance between production and building production capacity. Identify the key roles that you take on in life, and make time for each of them.

Habit 4:  Think Win/Win

Seek agreements and relationships that are mutually beneficial. In cases where a “win/win” deal cannot be achieved, accept the fact that agreeing to make “no deal” may be the best alternative. In developing an organizational culture, be sure to reward win/win behavior among employees and avoid inadvertantly rewarding win/lose behavior.


Habit 5:  Seek First to Understand, Then to Be Understood

First seek to understand the other person, and only then try to be understood. Stephen Covey presents this habit as the most important principle of interpersonal relations. Effective listening is not simply echoing what the other person has said through the lens of one’s own experience. Rather, it is putting oneself in the perspective of the other person, listening empathically for both feeling and meaning.

Continue reading

Tagged , , , ,

BackendPro – CodeIgniter Based Control Panel For Developers

Few days ago i found a new things (BackendPro) for developing control panel of  CodeIgniter Based web applications with more powerful and user friendly basic features. It is a control panel built using CodeIgniter. It is aimed at developers to be able to create powerful websites with little effort. Features include authentication, access control lists, asset management and more. Its not like a CMS where it provides you with a full working system but it does provide you with part of a system. It provides you with functionality to do all the simple repetitive tasks like authentication, permissions and a basic look and feel for your websites control panel. So using your current PHP and CodeIgniter knowledge you can use BackendPro to built a fully working website quickly since you can concentrate on your application instead of the bits to manage the system.

What can it do?

  • User Authentication with registration and account activation
  • User Permissions by using Access Control Lists (Has Access Control area to manage your websites access permissions)
  • Site Preferences (Stored in a database with simple to use UI to update and change preferences)
  • Improved Asset Library (Means loading assets onto pages is quick and simple, also has asset caching to speed up the loading of asset files)
  • PHP to javascript variable conversion (Easy way to pass PHP variables into your javascript scripts)
  • ReCAPTCHA
  • Status messages (Can display info/success/warning/error messages to the user)
  • Breadcrumb trail creation

For More details check the following URL

http://www.kaydoo.co.uk/

Tagged , , , ,

Install ionCube PHP Encoder on DreamHost Server

IonCube is a solution to encode php files so that nobody can see the code. IonCube is used to protect the programs written in PHP language from being viewed or edited. User have to have ionCube loader installed on the server for running ionCube encoded files.

There are situation where you need to run softwares encoded with ionCube. For running those kind of programs you need ionCube loader installed on your server.

Recently I was working on PHP Video Sharing Script (Vidiscript). I wanted to run it on my DreamHost account but that script needed ionCube loader installed on server. So I tried to find a way to install ionCube loader on the DreamHost account. I went to DreamHost wiki. I read the instructions and successfully install ionCube in my server. Few Days Later i need to install it again from my friends dreamhost account cause he was using a script which was encoded by ionCube. I did it again. But the steps what they write in their wiki, is littlebit hard for normal user. Its for advanced techie people. So i was looking for an easy way and finally I found readymade script made by sXi to install ionCube loader on DreamHost server. Continue reading

Tagged , , ,

Online Payments With Paypal (PHP)

Many small businesses and non-profit organizations hesitate to enter the online marketplace because of the mis-perceptions that online payment processing is risky for their users, expensive to implement, and integrate poorly with existing systems. In reality, with the advent of and subsequent improvement to Web services, the efficiency of fund transfer has greatly increased, providing an ideal way to handle nearly any volume of transactions through third-party vendors. eBay’s PayPal, among the most widely known, offers competitive rates and a workable PHP SDK to access its API.

The two payment methods allowed through the API are:
* Direct Payment: Use this to gather billing details on your Web site, charge the user’s credit card, and never leave your domain. Suited to large organizations that already have https secure applications and infrastructure for storing customer and cart information.

* Express Checkout: Users save time by using their PayPal account information as well as choose shipping methods, instead of reentering this information on your site. This approach frees your application from having to store a local copy of the buyer’s information, and can be conducted with a minimum of additional security infrastructure. Continue reading

Tagged , , ,

Wolfram Alpha – An interesting search engine !!!

May 15, 2009 will always be remembered as the day that Wolfram Alpha has been officially launched. Stephen Wolfram, a British scientist, and inventor of Mathematica, is the creator of Wolfram Alpha.

Wolfram Alpha is a different kind of search engine, actually it could be more precisely described as a computational knowledge engine. It is using inbuilt algorithms, and its huge knowledge base (trillions of pieces of data!), to compute queries in various topics, such as Mathematics, Physics, Chemistry, Engineering, Astronomy and more.

What kind of resources does Wolfram Alpha use?

Building and maintaining such a computationally intensive engine, requires a tremendous amount of resources.
The following resources had been gathered for the launch day:

– Five distributed co-location facilities
– Two supercomputers
– 10,000 processor cores
– Hundreds of terabytes of disks
– Lots of bandwidth
– Lots of cooling / air-conditioning

The result is the ability to handle 175 million queries (yielding maybe a billion) per day—over 5 billion queries (encompassing around 30 billion calculations) per month!

Continue reading

Tagged , , , ,

Classified WordPress Theme (CWT)

Here’s a new and unique WordPress theme developed by me. CWT is a premium WordPress theme for running a classifieds website.

Features:

  • User Submitted Classifieds – visitors are able to ad classifieds using a simple form on the site. You can set if users are required to register or not to publish something.
  • Managing Classifieds – You can edit / delete classifieds through the usual WordPress manage page. You can choose to publish classifieds automatically or if you want to approve them first!
  • Displaying Classifieds – classifieds are displayed in a clean / easy-to-read way. You can choose a currency, and certain icon for each category. It also display the sale item location in yahoo map view.
  • You can share the sale with your friends.
  • Usability – Easy to use listings layout, search box and an form for posting new classifieds
  • RSS Feeds – general RSS, a specific RSS feed for each category and with a bit of web knowledge you will be able to implement even a mail alert system.
  • No Plug-ins Required Continue reading
Tagged , , ,