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

Strategy design pattern


The Strategy design pattern exists to allow us to alter the behavior of an object at runtime.

Let's suppose we have a class that will raise a number to a power, but at runtime we want to alter whether we square or cube a number.

Let's start off by defining an interface a function that will raise a number to a given power:

<?php 
 
interface Power 
{ 
  public function raise(int $number): int; 
} 

We can accordingly define classes to Square and also Cube a given number by implementing the interface.

Here's our Square class:

<?php 
 
class Square implements Power 
{ 
  public function raise(int $number): int 
  { 
    return pow($number, 2); 
  } 
} 

And let's define our Cube class:

<?php 
 
class Cube implements Power 
{ 
  public function raise(int $number): int 
  { 
    return pow($number, 3); 
  } 
} 

We can now build a class that will essentially...