Sample of PHP: Design Patterns Adapter

About the Adapter

In the Adapter Design Pattern, a class converts the interface of one class to be what another class expects.

In this example we have a SimpleBook class that has a getAuthor() and getTitle() methods. The client, testAdapter.php, expects a getAuthorAndTitle() method. To “adapt” SimpleBook for testAdapter we have an adapter class, BookAdapter, which takes in an instance of SimpleBook, and uses the SimpleBook getAuthor() and getTitle() methods in it’s own getAuthorAndTitle() method.

Adapters are helpful if you want to use a class that doesn’t have quite the exact methods you need, and you can’t change the orignal class. The adapter can take the methods you can access in the original class, and adapt them into the methods you need.


//copyright Lawrence Truett and 2006, all rights reserved

  class SimpleBook {

    private $author;
    private $title;

    function __construct($author_in, $title_in) {
      $this->author = $author_in;
      $this->title  = $title_in;

    function getAuthor() {return $this->author;}

    function getTitle() {return $this->title;}

download source, use right-click and “Save Target As…” to save with a .php extension.


//copyright Lawrence Truett and 2006, all rights reserved


  class BookAdapter {

    private $book;

    function __construct(SimpleBook $book_in) {
      $this->book = $book_in;

    function getAuthorAndTitle() {
      return $this->book->getTitle() . ' by ' . $this->book->getAuthor();

download source, use right-click and “Save Target As…” to save with a .php extension.


//copyright Lawrence Truett and 2006, all rights reserved


  define('BR', '<'.'BR'.'>');

  echo BR;

  $book = new SimpleBook("Gamma, Helm, Johnson, and Vlissides",
                         "Design Patterns");

  $bookAdapter = new BookAdapter($book);

  echo 'Author and Title: '.$bookAdapter->getAuthorAndTitle();

  echo BR.BR;
download source, use right-click and “Save Target As…” to save with a .php extension.

output of testAdapter.php


Author and Title: Design Patterns by Gamma, Helm, Johnson, and Vlissides


Sample of PHP: Design Patterns Facade

About the Facade

In the facade pattern a class hides a complex subsystem from a calling class. In turn, the complex subsystem will know nothing of the calling class.

In this example, the CaseReverseFacade class will call a subsystem to reverse the case of a string passed from the Book class. The subsystem is controlled by the reverseCase function in the CaseReverseFacade, which in turn calls functions in the ArrayCaseReverse and ArrayStringFunctions classes. As written, the CaseReverseFacade can reverse the case of any string, but it could easily be changed to only reverse a single element of a single class.

In my example I make all elements of the Facade and the subsystem static. This could also easily be changed.


//copyright Lawrence Truett and 2005, all rights reserved
  class Book {
    private $author;
    private $title;
    function __construct($title_in, $author_in) {
      $this->author = $author_in;
      $this->title  = $title_in;
    function getAuthor() {return $this->author;}
    function getTitle() {return $this->title;}
    function getAuthorAndTitle() {
      return $this->getTitle() . ' by ' . $this->getAuthor();
download source, use right-click and “Save Target As…” to save with a .php extension.


//copyright Lawrence Truett and 2005, all rights reserved
  class CaseReverseFacade {
    public static function reverseStringCase($stringIn) {
      $arrayFromString = 
      $reversedCaseArray = 
      $reversedCaseString = 
	  return $reversedCaseString;
download source, use right-click and “Save Target As…” to save with a .php extension.


//copyright Lawrence Truett and 2005, all rights reserved
  class ArrayCaseReverse {
	private static $uppercase_array = 
	  array('A', 'B', 'C', 'D', 'E', 'F',
	        'G', 'H', 'I', 'J', 'K', 'L',
	        'M', 'N', 'O', 'P', 'Q', 'R',
	        'S', 'T', 'U', 'V', 'W', 'X',
	        'Y', 'Z');
	private static $lowercase_array = 
	  array('a', 'b', 'c', 'd', 'e', 'f',
	        'g', 'h', 'i', 'j', 'k', 'l',
	        'm', 'n', 'o', 'p', 'q', 'r',
	        's', 't', 'u', 'v', 'w', 'x',
	        'y', 'z');
    public static function reverseCase($arrayIn) {
      $array_out = array();

	  for ($x = 0; $x < count($arrayIn); $x++) {
	    if (in_array($arrayIn[$x], self::$uppercase_array)) {
          $key = array_search($arrayIn[$x], self::$uppercase_array);
		  $array_out[$x] = self::$lowercase_array[$key];
	    } elseif (in_array($arrayIn[$x], self::$lowercase_array)) {
          $key = array_search($arrayIn[$x], self::$lowercase_array);
		  $array_out[$x] = self::$uppercase_array[$key];
		} else {
		  $array_out[$x] = $arrayIn[$x];
	  return $array_out;
download source, use right-click and “Save Target As…” to save with a .php extension.


//copyright Lawrence Truett and 2005, all rights reserved
  class ArrayStringFunctions {
    public static function arrayToString($arrayIn) {
      $string_out = NULL;
	  foreach ($arrayIn as $oneChar) {
	    $string_out .= $oneChar;
	  return $string_out;
    public static function stringToArray($stringIn) {
      return str_split($stringIn);
download source, use right-click and “Save Target As…” to save with a .php extension.


//copyright Lawrence Truett and 2005, all rights reserved
  echo tagins("html");
  echo tagins("head");  
  echo tagins("/head");  
  echo tagins("body");
  echo tagins("br").tagins("br");

  $book = 
    new Book("Design Patterns",
	            "Gamma, Helm, Johnson, and Vlissides");
  echo "Original book title: ".$book->getTitle();
  echo tagins("br").tagins("br");
  $bookTitleReversed = 

  echo "Reversed book title: ".$bookTitleReversed;
  echo tagins("br").tagins("br");
  echo tagins("br");
  echo tagins("/body");
  echo tagins("/html");
  //doing this so code can be displayed without breaks
  function tagins($stuffing) {
    return "<".$stuffing.">";
download source, use right-click and “Save Target As…” to save with a .php extension.

output of testFacade.php

Original book title: Design Patterns
Reversed book title: dESIGNpATTERNS

Creating Web Service Using PHP Within 10 Minutes


Today, I am trying to write up on web service functionality and also how to consume it using PHP code. Basically, it is a very beginner level web service tip but you will gather knowledge step by step & easily run it on your server.


  1. What is SOAP?
  2. Why SOAP?
  3. Create web service method
  4. Consume web service


What is SOAP?

SOAP is based on XML so it is considered human read. It is a protocol for accessing a Web Service. It is a simple XML-based protocol to let applications exchange information over HTTP.


In real field, so many applications are required for data communication between systems by Remote Procedure Calls (RPC) between objects like DCOM and CORBA but HTTP was not designed for this.

  • RPC represents compatibility
  • Security problem
  • Firewalls and proxy servers will normally block this kind of traffic.

A better way to communicate between applications is over HTTP as HTTP is supported by all Internet browsers and servers. That’s why it is preferable to SOAP Service.

We can collaborate with other programmers building big size and complex applications in multiple platforms.

Using the Code

Here, I will create a web service using PHP code. So let’s follow the steps given below:

Step 1: You will download the library from

Step 2: Run WAMP server, then you will go to www root folder location.

Step 3: Create folder, it’s called “WebServiceSOAP” into www root folder.

Step 4: Paste “lib” folder inside your “www/WebServiceSOAP/” location from Step 1 download files.

Step 5: Create two files “server.php” and “client.php” into WebServiceSOAP folder location.

Step 6: Inside “server.php”, please write the code lines given below:

 Collapse | Copy Code
//call library 
require_once ('lib/nusoap.php'); 
//using soap_server to create server object 
$server = new soap_server; 

//register a function that works on server 

// create the function 
function get_message($your_name) 
return new soap_fault('Client','','Put Your Name!'); 
$result = "Welcome to ".$your_name .". Thanks for Your First Web Service Using PHP with SOAP"; 
return $result; 
// create HTTP listener 

Step 7: After creating “server.php” file, now we will test this server function. Please go to URL & typehttp://localhost/WebServiceSOAP/server.php?wsdl.

Step 8: Create “client.php” file into WebServiceSOAP folder location. Please find the following code lines:

 Collapse | Copy Code
require_once ('lib/nusoap.php'); 
//Give it value at parameter 
$param = array( 'your_name' => 'Monotosh Roy'); 
//Create object that referer a web services 
$client = new soapclient('http://localhost/WebServiceSOAP/server.php'); 
//Call a function at server and send parameters too 
$response = $client->call('get_message',$param); 
//Process result 
echo "FAULT: <p>Code: (".$client->faultcode."</p>"; 
echo "String: ".$client->faultstring; 
echo $response; 

Step 9: Save all codes, then please go to URL and type http://localhost/WebServiceSOAP/client.php.

 Collapse | Copy Code
Result: Welcome to Monotosh Roy. Thanks for Your First Web Service Using PHP with SOAP

So, today I have shown you how to use simple SOAP web service and to get message from service at client end.

How to Configure Nginx to Execute PHP Using PHP-FPM

Nginx is pronounced as “Engine-X”, which is a web server and reverse proxy server. Nginx is well known for its speed and ability to handle large number of requests simultaneously with optimal use of resources.

PHP-FPM stands for “PHP-FastCGI process manager”. CGI refers to the common gateway interface which is scripted to work as a interface between the web server and dynamic content serving programs. It listens on a port much like the web server itself does, and passes the request between the PHP and web server.

This tutorial provides instructions on how to install and configure Nginx with PHP-FPM, which will help you to execute PHP programs in Nginx.

As we discussed earlier in Apache vs Nginx, when compared to Nginx, Apache is relatively slow while handling heavy load and processing large number of requests.

1. Install Nginx

You can either install Nginx from source, or install it using the package management tool that comes with your distro.

For example, on Ubuntu you can install nginx using apt-get as shown below.

$ sudo apt-get install nginx

Start the nginx server as shown below:

$ sudo service nginx start

Go to http://{your-ip-address} and make sure you see the Nginx’s welcome page.

2. Install PHP5-FPM

Next, install php5-fpm using the package management tool that comes with your distro.

For example, on Ubuntu you can install php5-fpm using apt-get as shown below.

$ sudo apt-get install php5-fpm

3. Add PHP Configuration to Nginx

Next, modify the /etc/nginx/sites-available/default file, and add the following lines.

$ sudo vi /etc/nginx/sites-available/default
server {
  listen   80;
  root /usr/share/nginx/www;
  index index.php index.html index.htm;
  location / {
    try_files $uri $uri/ /index.html;
  error_page 404 /404.html;
  error_page 500 502 503 504 /50x.html;
  location = /50x.html {
    root /usr/share/nginx/www;
  # pass the PHP scripts to FastCGI server listening on
  location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;

4. Set listen Parameter in php5-fpm www.conf

Next, we need to make the following changes in the php-frpm configuration.

By default, you’ll see the following listen entry in the www.conf file

$ sudo vi  /etc/php5/fpm/pool.d/www.conf
listen =

In the www.conf file, leave everything as it is, and replace the above listen line with the one shown below.

$ sudo vi  /etc/php5/fpm/pool.d/www.conf
listen = /var/run/php5-fpm.sock

5. Restart the Nginx and PHP5-FPM and Test it

Restart php5-fpm and nginx as shown below

$ sudo service nginx restart

$ sudo service php5-fpm restart

Finally, create the following index.php file in the nginx document root, and test it.

$ sudo vi /usr/share/nginx/www
  phpinfo( );

Finally, open your browser and go to http://localhost/index.php (or use your ip-address), which will execute the index.php file and display the php information.

How To Install (LEMP) nginx, MySQL, PHP stack on Arch Linux

About Lemp

LEMP stack is a group of open source software to get web servers up and running. The acronym stands for Linux, nginx (pronounced Engine x), MySQL, and PHP. Since the server is already running Arch Linux, the linux part is taken care of. Here is how to install the rest.


The steps in this tutorial require the user to have root privileges. You can see how to set that up in the Initial Server Setup Tutorial in steps 3 and 4.

Step One—Pacman

Because pacman, the arch package manager, has a rolling package release, we should update Arch and its repositories before proceeding with any other steps:

sudo pacman -Syu

Step Two—Install MySQL

Once everything is fresh and up to date, we can start to install the server software, beginning with MySQL.

sudo pacman -S mysql

Once MySQL installs, start both mysql and the secure installation process. You will also be able to set the MySQL root password during the installation.

sudo systemctl start mysqld && mysql_secure_installation

When initially prompted for the MySQL root password, you can go ahead and press enter, as it has not yet been set. Your installation should look like this:

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorization.

Set root password? [Y/n] y
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!

By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
 ... Success!

By default, MySQL comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MySQL
installation should now be secure.

Thanks for using MySQL!

Follow up by restarting MySQL:

sudo systemctl restart mysqld

Step Three—Install nginx

Once MySQL is all set up, we can move on to installing nginx on the VPS.

sudo pacman -S nginx

nginx does not start on its own. To get nginx running, type:

sudo systemctl start nginx

You can confirm that nginx has installed an your web server by directing your browser to your IP address. You can run the following command to reveal your VPS’s IP address.

curl -s

Step Four—Install PHP-FPM

In order to process php application, we will need to install php-fpm.

sudo pacman -S php-fpm

Once its installed, start it up.

sudo systemctl start php-fpm

Finally, we need to tell nginx to run php using php-fpm. To accomplish this, first open up the nginx configuration file:

sudo nano /etc/nginx/nginx.conf

Find the location block that deals with php applications and replace the text in the section with the following:

location ~ \.php$ {
      fastcgi_pass   unix:/var/run/php-fpm/php-fpm.sock;
      fastcgi_index  index.php;
      root   /srv/http;
      include        fastcgi.conf;

Save, exit, and restart nginx:

sudo systemctl restart nginx

Step Five—Create a PHP Info Page

We can quickly see all of the details of the new php configuration.

To set this up, first create a new file:

sudo nano /srv/http/info.php

Add in the following line:


Then Save and Exit.

Restart nginx

sudo systemctl restart nginx

You can see the nginx and php-fpm configuration details by visiting http://youripaddress/info.php

Your LEMP stack is now set up and configured on your virtual private server.

Step Six—Configure the Daemons to Start at Boot

To ensure that all of the LEMP programs start automatically after any server restarts:

sudo systemctl enable nginx mysqld php-fpm

With that, LEMP is installed.

PHP – Sending Emails

PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function].

Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.

The configuration for Windows should look something like this:

[mail function]
; For Win32 only.

; For win32 only
sendmail_from =

Linux users simply need to let PHP know the location of their sendmail application. The path and any desired switches should be specified to the sendmail_path directive.

The configuration for Linux should look something like this:

[mail function]
; For Win32 only.

; For win32 only
sendmail_from = 

; For Unix only
sendmail_path = /usr/sbin/sendmail -t -i

Now you are ready to go:

Sending plain text email:

PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient’s email address, the subject of the the message and the actual message additionally there are other two optional parameters.

mail( to, subject, message, headers, parameters );

Here is the description for each parameters.

Parameter Description
to Required. Specifies the receiver / receivers of the email
subject Required. Specifies the subject of the email. This parameter cannot contain any newline characters
message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parameters Optional. Specifies an additional parameter to the sendmail program

As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed.

Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.


Following example will send an HTML email message to You can code this program in such a way that it should receive all content from the user and then it should send an email.

<title>Sending email using PHP</title>
   $to = "";
   $subject = "This is subject";
   $message = "This is simple text message.";
   $header = " \r\n";
   $retval = mail ($to,$subject,$message,$header);
   if( $retval == true )  
      echo "Message sent successfully...";
      echo "Message could not be sent...";

Sending HTML email:

When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.

While sending an email message you can specify a Mime version, content type and character set to send an HTML email.


Following example will send an HTML email message to copying it to You can code this program in such a way that it should recieve all content from the user and then it should send an email.

<title>Sending HTML email using PHP</title>
   $to = "";
   $subject = "This is subject";
   $message = "<b>This is HTML message.</b>";
   $message .= "<h1>This is headline.</h1>";
   $header = " \r\n";
   $header = " \r\n";
   $header .= "MIME-Version: 1.0\r\n";
   $header .= "Content-type: text/html\r\n";
   $retval = mail ($to,$subject,$message,$header);
   if( $retval == true )
      echo "Message sent successfully...";
      echo "Message could not be sent...";

Sending attachments with email:

To send an email with mixed content requires to set Content-type header tomultipart/mixed. Then text and attachment sections can be specified within boundaries.

A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email’s final section must also end with two hyphens.

Attached files should be encoded with the base64_encode() function for safer transmission and are best split into chunks with the chunk_split() function. This adds \r\n inside the file at regular intervals, normally every 76 characters.

Following is the example which will send a file /tmp/test.txt as an attachment. you can code your program to receive an uploaded file and send it.

<title>Sending attachment using PHP</title>
  $to = "";
  $subject = "This is subject";
  $message = "This is test message.";
  # Open a file
  $file = fopen( "/tmp/test.txt", "r" );
  if( $file == false )
     echo "Error in opening file";
  # Read the file into a variable
  $size = filesize("/tmp/test.txt");
  $content = fread( $file, $size);

  # encode the data for safe transit
  # and insert \r\n after every 76 chars.
  $encoded_content = chunk_split( base64_encode($content));

  # Get a random 32 bit number using time() as seed.
  $num = md5( time() );

  # Define the main headers.
  $header = "\r\n";
  $header .= "MIME-Version: 1.0\r\n";
  $header .= "Content-Type: multipart/mixed; ";
  $header .= "boundary=$num\r\n";
  $header .= "--$num\r\n";

  # Define the message section
  $header .= "Content-Type: text/plain\r\n";
  $header .= "Content-Transfer-Encoding:8bit\r\n\n";
  $header .= "$message\r\n";
  $header .= "--$num\r\n";

  # Define the attachment section
  $header .= "Content-Type:  multipart/mixed; ";
  $header .= "name=\"test.txt\"\r\n";
  $header .= "Content-Transfer-Encoding:base64\r\n";
  $header .= "Content-Disposition:attachment; ";
  $header .= "filename=\"test.txt\"\r\n\n";
  $header .= "$encoded_content\r\n";
  $header .= "--$num--";

  # Send email now
  $retval = mail ( $to, $subject, "", $header );
  if( $retval == true )
      echo "Message sent successfully...";
      echo "Message could not be sent...";

You try all the above examples. If you face any problem then you can post that problem in discussion forum.

How to improve PHP programming skills

“How do I improve my PHP skills?” is a recurring question on various boards and chats. It’s often asked by newbies but even experienced developers ask themselves the same thing. After all trying to be better is in the human nature. This is a deep question and when you think about it there isn’t a straight forward reply. Nevertheless I will try to give a comprehensive answer which hopefully is going to be useful not only to the beginners but also to the people with some commercial experience.

Matthew Syed in his book “Bounce” tells us that to reach an elite level in any discipline one has to practice for 10,000 hours (which is roughly 10 years). I don’t think that mastering PHP requires 10 years but practicing is essential. Obviously practice must be purposeful, otherwise it is useless.

The last sentence of the above paragraph is the key to sucess. It’s not only about what you have to do but also how are you doing it.

Make sure you’ve chosen the most effective way of learning. It will depend on your actual knowledge. Beginners might prefer direct interaction with people or follow video tutorials while experience developer could chose blogs, books or conferences.

Once you learn something new – practice it. It might require creating a proof of concept, a pet project or changing your habits. Stay curious and open minded. Don’t be afraid of breaking things. If you can check something yourself do it.

Although context of this post is PHP the question doesn’t have much to do with this particular language. Improving PHP skills means improving your universal programming skills. That can be broken down into 3 areas:
– engineering (coding standards, design patterns, unit testing, algorithms etc.)
– managing (application life cycle, version control, agile etc)
– environment (databases, operating system, networks, protocols etc)

Each person needs a different mixtures of the above skills – depends on what’s their ultimate goal. There are various senior positions for a developer but generally speaking all of them are either technical (head of development, senior architect etc) or commercial(development manager, CTO etc). The senior roles can be paid equally well so it’s a matter of choosing between science and business.

Ok, after this somewhat long introduction it’s the time to answer the question. To improve you PHP (or generally speaking web development) skills pick a point from the below list and try to learn as much as you can about it. You don’t have to follow the proposed order but ultimately you want to know everything from this list.

PHP programming
– PHP basics: variables, loops and functions
– Arrays (
– File system functions (

Font-end basics

Object oriented programming in PHP
– Classes and Objects (
– Exceptions (
– Namespaces (

Database basics
– SQL basics (select, insert, update, delete)

– JavaScript
– jQuery
– Responsive web design

– XML & DOM (
– Regular expressions (
– SPL (
– Magic Methods (
– GD (
– JSON (

– Database design (
– Indexing
– Maintenance (manage users, backups)
– SQL optimisation

Software design
– Design patterns (“PHP Objects, Patterns and Practice”)
– Algorithms and data structures (Introduction to Algorithms)
– Unit Testing (The Art of Unit Testing: with Examples in .NET)
– PHP Frameworks (one is enough)

Web application security
– MySQL injections
– Cross site scripting

Code managment
– Version control (SVN or GIT)
– Branching (
– Bug tracking (any available software)
– Coding standards (“Clean Code: A Handbook of Agile Software Craftsmanship”)

– Command line
– Installation and configuration of LAMP environment
– Installing PHP extensions

Apache web server
– Virtual Hosts
– MOD_Rewrite

Alternative storage
– Caching: Memcached or Redis
– NoSQL: MongoDB or CouchDB or Cassandra
– Search engine: SOLR or ElasticSearch

– OSI Model (
– TCP/IP protocol
– HTTP protocol
– Working with sniffers (tcpdump or wireshark)
– CURL (

Leading development
– SCRUM (“Agile Project Management with Scrum”)
– Leading (“How to Lead: What the best leaders know, do and say”)
– Test Driven development

I would like this list to be as useful as possible so I will be extending it with the time. If you feel I missed something or you would like to recommend a good tutorial please let me know.