How To Source Code A Singleton Design Pattern In PHP 5.

Singleton Design Pattern is a Creational Pattern.

Goal Of The Singleton Pattern

  • Ensure a class has only one instance and provide a global point to retrieve it.
  • The singleton is used to create only one single point of entry or functionality within a system or application.
  • The purpose of the singleton pattern is to have just one single instance of an object in the entire application.

Possible Usage Of Singleton Pattern

  • When creating a database layer – you would want one instance to communicate with your database. Thus helping in maintaining only one connection instance instead of multiple one which might otherwise be resource consuming.
  • When you have a big/complex system going on; singleton helps in maintaining a synchronized state within your system. For example logged in a application make a great deal use of singleton within their respective application.
  • When you observe that most of the methods you are accessing within your projects, come from one recurring object. This is a candidate for being a singleton.

Anatomy Of A Singleton Pattern In A PHP

You need to have these conditions fulfilled:

  • A static member variable/ properties – as a properties for the instance of that class
  • Locked down the constructor of that class – simply by making it’s visibility private
  • Prevent any object or instance of that class to be cloned, that is to prevent any entity within the system to make copy of this object – make it visibility private.
  • Have a single globally accessible static method to access/retrieve the instance of that class – a public static method

Let’s implement all these things into codes :


class MyTestSingleton {

///Condition 1 - Presence of a static member variable
private static $_instance = null;
///Condition 2 - Locked down the constructor
private function __construct() {} //Prevent any oustide instantiation of this class
///Condition 3 - Prevent any object or instance of that class to be cloned
private function __clone() {} //Prevent any copy of this object

///Condition 4 - Have a single globally accessible static method 13.
public static function getInstance() {
if(self::$_instance == null){
self::$_instance = new MyTestSingleton();
echo "For first time enter this block at same session or same execution time
return self::$_instance;
///Now we are all done, we can now proceed to have any other method logic we want

public function getHello(){
echo "
Hello, This method is called by using a singleton object/Instance";

///Testing some calls to that class
$obj1 = MyTestSingleton::getInstance();
$obj2 = MyTestSingleton::getInstance();
$obj3 = MyTestSingleton::getInstance();
$obj4 = MyTestSingleton::getInstance();

I believe, Singleton is very useful design pattern.


What’s the SQL Injection.?

An SQL Injection can destroy your database.

SQL Injection

SQL injection is a technique where malicious/harmful users can inject SQL commands into an SQL statements, via web page input.
Injected SQL commands can alter SQL statement and compromises the security of a web application.

1. SQL Injection Based on 1=1 is Always True.

txtUserId = getRequestString(“UserId”);
txtSQL = “SELECT * FROM Users WHERE UserId = ” + txtUserId;
txtUserId = 105 or 1=1;
SELECT * FROM Users WHERE UserId = 105 or 1=1;

2. SQL Injection Based on “”=”” is Always True.

uName = getRequestString(“UserName”);
uPass = getRequestString(“UserPass”);
sql = “SELECT * FROM Users WHERE Name ='” + uName + “‘ AND Pass ='” + uPass + “‘”

SELECT * FROM Users WHERE Name =”” or “”=”” AND Pass =”” or “”=””
The result SQL is valid. It will return all rows from the table Users, since WHERE “”=”” is always true.

3. SQL Injection Based on Batched SQL.

txtUserId = getRequestString(“UserId”);
txtSQL = “SELECT * FROM Users WHERE UserId = ” + txtUserId;
txtUserId = 105; DROP TABLE Suppliers

SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers.

Difference between PHP4 and PHP5.

Here are some major differences between PHP4 and PHP5 that you need to know:

1. Unified Constructors and Destructors:

In PHP4, constructors had same name as the class name. This used to cause overhead because every time you changed the class name, you had to change all the occurrences of that name.

In PHP5, you simply need to name your constructors as __construct(). (the word ‘construct’ prefixed by double underscores). Similarly you can name your destructors as __destruct(). (the word ‘destruct’ prefixed by double underscores.) In destructors, you can write code that will get executed when the object is destroyed.

2. Abstract Class:

PHP5 lets you declare a class as ‘Abstract’. (i.e. a class whose object cannot be created. You can only extend an abstract class) Also, a class must be defined as abstract if it contains any abstract methods. And those abstract methods must be defined within the class which extend that abstract class. You can include complete method definitions within the abstract methods of abstract class.

3. Final Keyword:

PHP5 allows you to declare a class or method as ‘Final’ now. You just need to use ‘final’ keyword that will indicate that the class cannot be inherited or the method cannot be overridden.

4. Exception Handling:

PHP5 has introduced ‘exceptions’. An exception is simply a kind of error and the ‘exception error’ can be handled in an exception object. By using an exception, one can gain more control over the simple trigger_error notices we were stuck with before.

When you are about to perform something ‘risky’ in your code, you can surround your code with a ‘try…catch’ block. First you surround your code in a ‘try {…….}’ block, then if an exception is thrown, your following ‘catch{……}’ block is there to intercept the error and handle it accordingly. You can write some PHP code in your ‘catch’ block which will get executed when an error occurs in the ‘try’ block. If there is no ‘catch’ block, a fatal error occurs.

PHP 5.5 and later, a finally block may also be specified after the catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.

The thrown object must be an instance of the Exception class or a subclass of Exception.
Example #2 Exception handling with a finally block
getMessage(), “\n”;
} finally {
echo “First finally.\n”;

try {
echo inverse(0) . “\n”;
} catch (Exception $e) {
echo ‘Caught exception: ‘, $e->getMessage(), “\n”;
} finally {
echo “Second finally.\n”;

// Continue execution
echo “Hello World\n”;

The above example will output:
First finally.
Caught exception: Division by zero.
Second finally.
Hello World

5. E_STRICT Error Level:

PHP5 introduces new error level defined as ‘E_STRICT’ (value 2048). This error levels notifies you when you use depreciated PHP code. It is not included in E_ALL, if you wish to use this new level you must specify it explicitly.

6. Autoloading (the __autoload() function):

PHP5 introduces a special function called ‘__autoload()’ (the word ‘autoload’ prefixed by double underscores). This function allows you to avoid writing a long list of includes at the top of your script by defining them inside this function. So you can automatically load object files when PHP encounters a class that hasn’t been defined yet.


function __autoload ($class_name) {

include $class_name . ‘.php’;


7. Visibility:

In PHP5, class methods and properties now have ‘visibility’. There are 3 levels of visibilities:

Public: ‘Public’ is the most visible. Methods are accessible to everyone including objects outside the classes. And properties readable and writable by everyone including objects outside the classes.
Private: ‘Private’ makes class members only available to the class itself.
Protected: ‘Protected’ makes class members accessible to the class itself and any inherited class (subclass) as well as any parent classes.

PHP4′s method of declaring a variable as ‘var’ keyword is still supported in PHP5. The ‘var’ keyword is now a synonym for the ‘public’ keyword now.

8. Pass by Reference:

In PHP4, everything was passed by value, including objects. Whereas in PHP5, all objects are passed by reference. Take a look at this PHP4 code for example –

$peter = new Person();
$peter->sex = ’male’;

$maria = $peter;
$maria->sex = ’female’;

echo $peter->sex; // This will output ‘female’

As you can see in the code above, if you wanted to duplicate an object in PHP4, you simply copied it by assigning it to another variable (Pass by value). But now in PHP5 you must use the new ‘clone’ keyword. So the above PHP4 code, will now look like this in PHP5 –

$peter = new Person();
$maria = new Person();

$peter->sex = ’male’;

$maria = clone $peter;
$maria->sex = ’female’;

echo $peter->sex; // This will output ‘female’

9. Interfaces:

It’s also possible for interfaces to have constants.

PHP5 introduces ‘interfaces’ . An interface defines the methods a class must implement. All the methods defined in an interface must be public. An interface helps you design common APIs. It is not designed as a blueprint for classes, but just a way to standardize a common API. A big advantage of using interfaces is that a class can implement any number of interfaces. You can still only ‘extend’ on parent class, but you can ‘implement’ an unlimited number of interfaces.

10. Class Constants and Static Methods/Properties:
It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don’t use the $ symbol to declare or use them.

The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.
It’s also possible for interfaces to have constants.
As of PHP 5.3.0, it’s possible to reference the class using a variable. The variable’s value can not be a keyword (e.g. self, parent and static).


echo $class::CONSTANT.”\n”; // As of PHP 5.3.0

Static methods and properties are also available. When you declare a class member as static, then it makes that member accessible (through the :: operator) without an instance. (Note this means within methods, the $this variable is not available).
For compatibility with PHP 4, if no visibility declaration is used, then the property or method will be treated as if it was declared as public.
Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.
Static properties cannot be accessed through the object using the arrow operator ->.

Calling non-static methods statically generates an E_STRICT level warning.

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

staticValue() . “\n”;
print $foo->my_static . “\n”; // Undefined “Property” my_static

print $foo::$my_static . “\n”;
$classname = ‘Foo’;
print $classname::$my_static . “\n”; // As of PHP 5.3.0

print Bar::$my_static . “\n”;
$bar = new Bar();
print $bar->fooStatic() . “\n”;

11. Traits :
As of PHP 5.4.0, PHP implements a method of code reuse called Traits.
Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

12. Type Hinting :

PHP 5 introduces type hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype), interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

If class or interface is specified as type hint then all its children or implementations are allowed too.

Type hints can not be used with scalar types such as int or string. Resources and Traits are not allowed either.

Example #1 Type Hinting examples

* Another test function
* First parameter must be an array
public function test_array(array $input_array) {

* First parameter must be iterator
public function test_interface(Traversable $iterator) {
echo get_class($iterator);

* First parameter must be callable
public function test_callable(callable $callback, $data) {
call_user_func($callback, $data);

// Another example class
class OtherClass {
public $var = ‘Hello World’;

Failing to satisfy the type hint results in a catchable fatal error.

// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;

// Fatal Error: Argument 1 must not be null

// Works: Prints Hello World

// Fatal Error: Argument 1 must be an array
$myclass->test_array(‘a string’);

// Works: Prints the array
$myclass->test_array(array(‘a’, ‘b’, ‘c’));

// Works: Prints ArrayObject
$myclass->test_interface(new ArrayObject(array()));

// Works: Prints int(1)
$myclass->test_callable(‘var_dump’, 1);

Type hinting also works with functions:

// Works
$myclass = new MyClass;

Type hinting allowing NULL value:

Software Design Principles

Software design principles represent a set of guidelines that helps us to avoid having a bad design. There are 3 important characteristics of a bad design that should be avoided:

Rigidity – It is hard to change because every change affects too many other parts of the system.
Fragility – When you make a change, unexpected parts of the system break.
Immobility – It is hard to reuse in another application because it cannot be disentangled from the current application.

Open Close Principle

Software entities like classes, modules and functions should be open for extension but closed for modifications.

OPC is a generic principle. You can consider it when writing your classes to make sure that when you need to extend their behavior you don�t have to change the class but to extend it. The same principle can be applied for modules, packages, libraries. If you have a library containing a set of classes there are many reasons for which you�ll prefer to extend it without changing the code that was already written (backward compatibility, regression testing, �). This is why we have to make sure our modules follow Open Closed Principle.

When referring to the classes Open Close Principle can be ensured by use of Abstract Classes and concrete classes for implementing their behavior. This will enforce having Concrete Classes extending Abstract Classes instead of changing them. Some particular cases of this are Template Pattern and Strategy Pattern.

May be design patterns has three types as following

1. Creational Design Patterns:
A. Singleton Pattern
B. Factory Pattern
C. Factory Method Pattern
D. Abstract Factory
2. Behavioral Design Patterns:
A. Observer Pattern
B. Chain of Responsibility
C. Command Pattern
D. Iterator
E. Interpreter
3. Structural Design Patterns:
A. Adapter Pattern
B. Bridge Pattern
C. Composite Pattern
D. Decorator Pattern
E. Proxy Pattern

I will have continue…………..this Article……………..

How to Post Data one apps to another apps with cURL by PHP

Do you want to post data one website to another website using PHP ? It’s actually pretty easy to do. Here’s the code.

“last_name” => “Ahsan”,
“email” => “bdparul@gmail”,

$ch = curl_init ($url_to_post);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $data_to_post);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$return_data = curl_exec ($ch);

And what happened? Here’s my quick explanation.


The url where you want to post your data to


The post data as an associative array. The keys are the post variables

$ch = curl_init ($url_to_post);

Initializes cURL
Initializes a new session and return a cURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions.

curl_setopt ($ch, CURLOPT_POST, true);

Tells cURL that we want to send post data

curl_setopt ($ch, CURLOPT_POSTFIELDS, $data_to_post);

Tells cURL what are post data is

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

Tells cURL to return the output of the post

$returndata = curl_exec ($ch);

Executes the cURL and saves theoutput in $return_data
Execute the given cURL session.
This function should be called after initializing a cURL session and all the options for the session are set.

Closes a cURL session and frees all resources. The cURL handle, ch, is also deleted.
Helpfull Link
That’s it. I believe it’s assist you.

Access visibility of public, protected, and private Properties/Members in PHP.

A key paradigm in OOP is encapsulation and access protection of object properties (also referred to as member variables). Most common OO languages have three main access restriction keywords: public, protected, and private. When defining a class member in the class definition, the developer needs to specify one of these three access modifiers before declaring the member itself. In case you are familiar with PHP 3 or 4’s object model, all class members were defined with the var keyword, which is equivalent to public in PHP 5. var has been kept for backward compatibility, but it is deprecated, thus, you are encouraged to convert your scripts to the new keywords:

class MyClass {

public $publicMember = “Public member”;

protected $protectedMember = “Protected member”;

private $privateMember = “Private member”;

function myMethod(){

// …



$obj = new MyClass();

This example will be built upon to demonstrate the use of these access modifiers.

First, the more boring definitions of each access modifier:

public. Public members can be accessed both from outside an object by using $obj->publicMember and by accessing it from inside the myMethod method via the special $this variable (for example, $this->publicMember). If another class inherits a public member, the same rules apply, and it can be accessed both from outside the derived class’s objects and from within its methods.

protected. Protected members can be accessed only from within an object’s method—for example, $this->protectedMember. If another class inherits a protected member, the same rules apply, and it can be accessed from within the derived object’s methods via the special $this variable.

private. Private members are similar to protected members because they can be accessed only from within an object’s method. However, they are also inaccessible from a derived object’s methods. Because private properties aren’t visible from inheriting classes, two related classes may declare the same private properties. Each class will see its own private copy, which are unrelated.

Usually, you would use public for members you want to be accessible from outside the object’s scope (i.e., its methods), and private for members who are internal to the object’s logic. Use protected for members who are internal to the object’s logic, but where it might make sense for inheriting classes to override them:

class MyDbConnectionClass {

public $queryResult;

protected $dbHostname = “localhost”;

private $connectionHandle;

// …


class MyFooDotComDbConnectionClass extends MyDbConnectionClass {

protected $dbHostname = “”;


This incomplete example shows typical use of each of the three access modifiers. This class manages a database connection including queries made to the database:

The connection handle to the database is held in a private member, because it is used by the class’s internal logic and shouldn’t be accessible to the user of this class.

In this example, the database hostname isn’t exposed to the user of the class MyDbConnectionClass. To override it, the developer may inherit from the initial class and change the value.

The query result itself should be accessible to the developer and has, therefore, been declared as public.

Note that access modifiers are designed so that classes (or more specifi-cally, their interfaces to the outer world) always keep an is-a relationship during inheritance. Therefore, if a parent declares a member as public, the inheriting child must also declare it as public. Otherwise, the child would not have an is-a relationship with the parent, which means that anything you can do with the parent can also be done with the child.

Some basic command of Ruby on Rails.

Ruby on Rails has three environment. So there has three command set environment of your Ruby on Rails.

1. set RAILS_ENV=production
2. set RAILS_ENV=development
3. set RAILS_ENV=test

Ruby on Rails development mode work as a default environment.

#Create Rails controller and action/function/method name command
rails generate controller controllerName action1 action2 action3
#Create Rails model and their fields name command
rails generate model modeleName fieldName:dataType fieldName:dataType

#Creating the Database command
rake db:create
#Database migrate command
rake db:migrate

#Starting up the Web Server command
rails server or rails s

Blog::Application.routes.draw do

# You can have the root of your site routed with “root”
# just remember to delete public/index.html.
root :to => “home#index”

The root :to => “home#index” tells Rails to map the root action to the home controller’s index action.


Learn to basic knowledge about of Ruby on Rails

Rails is a web-application framework of Ruby language that includes everything needed to create database-backed web applications according to the Model-View-Control pattern. Also it’s can do desktop( application.

## Installation guide line as follows
** Download latest stable version at Ruby on Rails,
** For windows OS need to Development Kit (
** Also here(
installation guide of Development Kit for your Ruby on Rails on windows computer.

if you want, you can follows this ( link for install Ruby on Rails.

== Getting Started

1. At the command prompt, create a new Rails application:
rails new myapp (where myapp is the application name)

2. Change directory to myapp and start the web server:
cd myapp; rails server (run with –help for options)

3. Go to http://localhost:3000/ and you’ll see:
“Welcome aboard: You’re riding Ruby on Rails!”

4. Follow the guidelines to start developing your application. You can find
the following resources handy:

* The Getting Started Guide:
* Ruby on Rails Tutorial Book:

I believe, it’s help you if you can play on Ruby on Rails.

What’s is the Test Driven Development (TDD)?

Test Driven Development (TDD)

The steps of test first development (TFD). The first step is to quickly add a test, basically just enough code to fail. Next you run your tests, often the complete test suite although for sake of speed you may decide to run only a subset, to ensure that the new test does in fact fail. You then update your functional code to make it pass the new tests. The fourth step is to run your tests again. If they fail you need to update your functional code and retest. Once the tests pass the next step is to start over (you may first need to refactor any duplication out of your design as needed,
turning TFD into TDD).

TDD with this simple formula:

TDD = Refactoring + TFD.

What is stdClass in PHP?

There has some points about of stdClass in PHP.

1.stdClass is php’s generic empty class
2.It is useful for anonymous objects, dynamic properties, etc. stdClass object can be created from the use of json_decode() as well.

PHP stdClass: Storing Data in an Object Instead of an Array

Have you ever wondered how that was done? Using PHP’s stdClass feature you can create an object, and assign data to it, without having to formally define a class.

Suppose you wanted to quickly create a new object to hold some data about a book. You would do something like this:

$book = new stdClass;
$book->title = “Harry Potter and the Prisoner of Azkaban”;
$book->author = “J. K. Rowling”;
$book->publisher = “Arthur A. Levine Books”;
$book->amazon_link = “;;

You can then access the data by calling $book->title and so on.

Or what if you wanted to take an array and turn it into an object? You can do that by casting the variable.

$array = array(
“title” => “Harry Potter and the Prisoner of Azkaban”,
“author” => “J. K. Rowling”,
“publisher” => “Arthur A. Levine Books”,
“amazon_link” => “;

$books = (object) $array;

This should produce the same result as the previous code snippet. You could also go the other direction, casting an object into an array by using $array = (array) $object.

Objects are really useful when you’re working with a large data structure, as you can have an object with nested sub-arrays in it, as SimpleXML tends to return. You get most of the data as properties of the result set object, and the posts in an RSS feed are assigned to array entries, which then have further objects inside them.