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

Chapter 1. Why "Good PHP Developer" Isnt an Oxymoron

Back in 2010, MailChimp published a post on their blog, entitled Ewww, You Use PHP? In this blog post, they described the horror when they explained their choice of PHP to developers who consider the phrase good PHP programmer an oxymoron. In their rebuttal they argued that their PHP wasn't your grandfathers PHP and that they use a sophisticated framework. I tend to judge the quality of PHP on the basis of, not only how it functions, but how secure it is and how it is architected. This book focuses on ideas of how you should architect your code. The design of software allows for developers to ease the extension of the code beyond its original purpose, in a bug-free and elegant fashion.

As Martin Fowler put it:

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand."

This isn't just limited to code style, but how developers architect and structure their code. I've encountered many developers with their noses constantly stuck in the documentation, copying and pasting bits of code until it works; hacking snippets together until it works. Moreover, I far too often see the software development process rapidly deteriorate as developers ever more tightly couple their classes with functions of ever increasing length.

Software engineers mustn't just code software; they must know how to design it. Indeed often a good software engineer, when interviewing other software engineers will ask questions about the design of the code itself. It is trivial to get a piece of code that will execute, and it is also benign to question a developer as to whether strtolower or str2lower is the correct name of a function (for the record, it's strtolower). Knowing the difference between a class and an object doesn't make you a competent developer; a better interview question would, for example, be how one could apply subtype polymorphism to a real software development challenge. Failure to assess software design skills dumbs down an interview and results in there being no way to differentiate between those who are good at it, and those who aren't. These advanced topics will be discussed throughout this book, by learning these tactics, you will better understand what the right questions to ask are when discussing software architecture.

Moxie Marlinspike once tweeted the following:

"As a software developer, I envy writers, musicians, and filmmakers. Unlike software, when they create something it is really done, forever".

When developing software, we mustn't forget we are authors, not just of instructions for a machine, but we are also authoring something that we later expect others to extend upon. Therefore, our code mustn't just be targeted at machines, but humans also. Code isn't just poetry for a machine, it should be poetry for humans also.

This is, of course, better said than done. In PHP, this may be found especially difficult given the freedom PHP offers developers on how they may architect and structure their code. By the very nature of freedom, it may be both used and abused, so it is true with the freedom offered in PHP.

Therefore, it is increasingly important that developers understand proper software design practices to ensure their code maintains the long term maintainability. Indeed, another key skill lies in refactoring code, improving the design of existing code to make it easier to extend in the long term.

Technical debt, the eventual consequence of poor system design, is something that I've found comes with the career of a PHP developer. This has been true for me whether it has been dealing with systems that provide advanced functionality or simple websites. It usually arises because a developer elects to implement a bad design for a variety of reasons; this is when adding functionality to an existing codebase or taking poor design decisions during the initial construction of software. Refactoring can help us address these issues.

SensioLabs (the creators of the Symfony framework) have a tool called  Insight that allows developers to calculate the technical debt in their own code. In 2011, they did an evaluation of technical debt in various projects using this tool; rather unsurprisingly they found that WordPress 4.1 topped the chart of all platforms they evaluated with them claiming it would take 20.1 years to resolve the technical debt that the project contains.

Those familiar with the WordPress core may not be surprised by this, but this issue of course is not only associated to WordPress. In my career of working with PHP, from working with security critical cryptography systems to working with systems that work with mission critical embedded systems, dealing with technical debt comes with the job. Dealing with technical debt is not something to be ashamed of for a PHP developer, indeed some may consider it courageous. Dealing with technical debt is no easy task, especially in the face of an ever more demanding user base, client, or project manager; constantly demanding more functionality without being familiar with the technical debt the project has associated to it.

I recently e-mailed the PHP Internals group as to whether they should consider deprecating the error suppression operator @. When any PHP function is prepended by an @ symbol, the function will suppress an error returned by it. This can be brutal, especially where that function renders a fatal error that stops the execution of the script, making debugging a tough task. If the error is suppressed, the script may fail to execute without providing developers a reason as to why this is. Usage of this operator may be described as an anti-pattern in some situations, something we will cover in Chapter 4, Structural Design Patterns.

Despite the fact that no one objected to the fact that there were better ways of handling errors (try/catch, proper validation) than abusing the error suppression operator and that deprecation should be an eventual aim of PHP, it is the case that some functions return needless warnings even though they already have a success/failure value. This means that due to technical debt in the PHP core itself, this operator cannot be deprecated until a lot of other prerequisite work is done. In the meantime, it is down to developers to decide the best methodologies of handling errors. Until the inherent problem of unnecessary error reporting is addressed, this operator cannot be deprecated. Therefore, it is down to developers to be educated as to the proper methodologies that should be used to address error handling and not to constantly resort to using an @ symbol.

Fundamentally, technical debt slows down development of a project and often leads to code being deployed that is broken as developers try and work on a fragile project.

When starting a new project, never be afraid to discuss architecture as architecture meetings are vital to developer collaboration; as one Scrum Master I've worked with said in the face of criticism that "meetings are a great alternative to work", he said "meetings are work...how much work would you be doing without meetings?".

In the rest of this chapter, we will cover the following points:

  • Coding style - the PSR standards

  • Revising object-oriented programming

  • Setting up the environment with Composer

  • Who are the Gang of Four?