Book Image

Mastering PHP Design Patterns

By : Junade Ali
Book Image

Mastering PHP Design Patterns

By: Junade Ali

Overview of this book

Design patterns are a clever way to solve common architectural issues that arise during software development. With an increase in demand for enhanced programming techniques and the versatile nature of PHP, a deep understanding of PHP design patterns is critical to achieve efficiency while coding. This comprehensive guide will show you how to achieve better organization structure over your code through learning common methodologies to solve architectural problems. You’ll also learn about the new functionalities that PHP 7 has to offer. Starting with a brief introduction to design patterns, you quickly dive deep into the three main architectural patterns: Creational, Behavioral, and Structural popularly known as the Gang of Four patterns. Over the course of the book, you will get a deep understanding of object creation mechanisms, advanced techniques that address issues concerned with linking objects together, and improved methods to access your code. You will also learn about Anti-Patterns and the best methodologies to adopt when building a PHP 7 application. With a concluding chapter on best practices, this book is a complete guide that will equip you to utilize design patterns in PHP 7 to achieve maximum productivity, ensuring an enhanced software development experience.
Table of Contents (14 chapters)
Mastering PHP Design Patterns
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface

Setting up the environment with Composer


Composer is a dependency manager for PHP, strongly inspired by Node's NPM and Bundler. It has now become integral to multiple PHP projects, including Laravel and Symfony. Why it is useful for us, however, is that it contains autoload functionality that is compliant with the PSR-0 and PSR-4 standards. You can download and install Composer from http://getcomposer.org.

Note

In order to install Composer globally on Mac OS X or Linux, first you can run the installer:

curl -sS https://getcomposer.org/installer | php

And then you can move Composer to install it globally:

mv composer.phar /usr/local/bin/composer

If the command preceding fails due to a permissions issue, rerun the command except putting sudo at the very start. You'll be asked to enter your password after you type the command, just enter it and hit Enter.

Once you've installed Composer by following the preceding steps, you can run it simply by running the composer command.

In order to install Composer on Windows it is easiest to just run the installer on the Composer website; currently you can find it at:

https://getcomposer.org/Composer-Setup.exe.

Composer is fairly easy to update, just run this command:

Composer self-update

Composer works by using the configuration in a file called composer.json, where you can outline external dependencies and your autoloading style. Once Composer has installed dependencies listed in this file, it writes a composer.lock file that details the exact versions it has installed. When using version control it is important that you commit this file (alongside the composer.json file), don't add it to your .gitignore file if you're on Git. This is very important because the lock file details the exact version of a package that was installed at a particular time in your version control system. You can, however, exclude a directory called vendor, I'll explain what that does later.

Let's start off by creating a file called composer.json in our project directory. This file is structured in JSON, so let me just remind you of how JSON works:

  • JSON consists of key/value pairs of data, think of it like a set of variables being defined in a file

  • A key value pair is comma separated, for example, "key" : "value"

  • Curly brackets hold objects

  • Square brackets hold arrays

  • Multiple pieces of data must be comma separated, without leaving a trailing comma at the end of the data

  • Keys and values that include strings must be wrapped in quotes

  • A backslash \ is the escape key

So now we can add the following markup to the composer.json file:

{ 
  "autoload": { 
    "psr-4": { 
      "IcyApril\\ChapterOne": "src/" 
    } 
  } 
} 

So let me explain what this file does; it tells Composer to autoload everything in the src/ directory into the IcyApril\ChapterOne namespace using the PSR-4 standard.

So, the next step is to create our src directory where we include the code we want to autoload. Done that? Right, now let's open up our command line and move into the directory where we've put our composer.json file.

In order to install everything in the composer.json file in your project just run the composer install command. For subsequent updates, the composer update command will update to the latest versions of all dependencies as defined in composer.json. If you don't want to do this, though, there is an alternative; running the composer dump-autoload command will solely regenerate the list of the PSR-0/PSR-4 classes that need to be included in the project (for example, you add, delete, or rename some of your classes).

Now let me cover how you will actually go about creating a class. So, let's create an src directory in our project and in that src directory create a new class called Book. You can do this by creating a file called Book.php. In that file, add something like this:

<?php 
namespace IcyApril\ChapterOne; 
 
class Book 
{ 
  public function __construct() 
  { 
    echo "Hello world!"; 
  } 
} 

This is a standard class, except we're just defining a constructor that will echo Hello world! when the class is instantiated.

As you may have noticed, we've followed a few naming conventions; firstly, the PSR-1 standard declares that class names must be declared in StudlyCaps. PSR-2 has a few extra requirements; to name a few: four spaces instead of a tab, one blank space after a namespace or use declarations, and placing brackets on new lines. It's definitely worth taking the time to read these standards if you haven't already. You might not agree with every standard, you might have a subjective preference to how you format your own code; my advice is to put these preferences aside for the greater good. Having code that is standardized by means of utilizing the PSR standards offers great advantages when collaborating on common code bases. The benefit of having an external standard, built by an organization such as the PHP-FIG group, is that you have your configuration pre-built into your IDE (for example, PHPStorm supports PSR-1/PSR-2 out of the box). Not only this but, when it comes to formatting arguments you have a concrete impartial document that outlines how things should be done, which is great for stopping religious code formatting arguments during code reviews.

Now that we've created the class we can go ahead and run the composer dump-autoload command in order to refresh our autoloader script.

So, we've configured our Composer autoloader and we've also got a test class to play around with, but the next question is how we can implement this. So, let's go ahead and implement this. In the same directory where we've implemented our composer.json file, let's add our index.php file.

The line after you put in your PHP opening tag, we need to pull in our autoloader script:

require_once('vendor/autoload.php'); 

Then we can instantiate our Book class:

new \IcyApril\ChapterOne\Book(); 

Set up your web server, point your document root to the folder we created, direct your web browser to your chosen web server and you should see Hello world! pop up on screen. Now you can take apart the code and play around with it.

The completed code sample is available alongside this book, so you can open it up and play around with it directly from there, just in case you need any help debugging your code.

Whether your classes are abstract classes or mere interfaces, when autoloading we treat them all as classes.