38,39 €
Develop robust and reusable code using a multitude of design patterns for PHP 7
This book is for PHP developers who wish to have better organization structure over their code through learning common methodologies to solve architectural problems against a backdrop of learning new functionality in PHP 7.
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.
The book covers advanced design patterns in detail in PHP 7 with the help of rich code-based examples.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 283
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: September 2016
Production reference: 1230916
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-713-0
www.packtpub.com
Author
Junade Ali
Copy Editor
Safis Editing
Reviewer
Sworup Shakya
Project Coordinator
Suzanne Coutinho
Commissioning Editor
Kunal Parikh
Proofreader
Safis Editing
Acquisition Editor
Chaitanya Nair
Indexer
Tejal Daruwale Soni
Content Development Editor
Nikhil Borkar
Production Coordinator
Aparna Bhagat
Technical Editor
Hussain Kanchwala
Cover Work
Aparna Bhagat
Junade Ali was a technical lead at some of the UK's leading digital agencies and has also worked using PHP in mission-critical road-safety systems. He loves pushing PHP to its innovative limits. Having started his career as a web development apprentice, he still remains engaged in the academic computer science community.
Junade, an avid contributor to the PHP community, has also spoken at PHPTek and the Lead Developer Conference. In addition to this, Junade was interviewed by Cal Evans for Voices of the ElePHPant, and he has appeared on the PHP Roundtable. In this spirit, Junade is proud of his local PHP user group: PHPWarks. Currently, Junade works at CloudFlare as a polymath, and helps make the Internet more secure and faster.
Outside of development, Junade has an interest in law and political campaigns and is a published author on constitutional law.
Sworup Shakya has worked as a web developer for more than ten years. He started his career as a Flash ActionScript developer, before moving on to ASP.NET MVC, and finally to PHP. During his time as a developer, Sworup worked extensively with frameworks, be it ASP.NET MVC or AngularJS or Laravel. However, while he was working as an ActionScript developer, he had to create one, which gave him knowledge of design patterns and OOP concepts that has helped him improve in order to be able to work on the frameworks he had to work on later.
Sworup received his Bachelor of Information Technology degree from Purbanchal University in Nepal. He currently works with Zimris Technologies Nepal Pvt. Ltd., a subsidiary of Zimris, LLC, as a senior developer.
Sworup likes to keep on top of the current technologies, keeping an eye on StackOverflow, Laracasts forums, and occasional podcasts. He posts on these mediums whenever he can and is looking to start a technical blog documenting his experiences at http://sworup.com.np/. You can reach him at [email protected].
I would like to thank Suzanne Coutinho, Francina Pinto and Chaitanya Nair of Packt Publishing for giving me this opportunity and helping me through the review process. I would like to thank my friends, family and colleagues for their unconditional support.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Have you ever been to a PHP conference? If not, I’d highly recommend it, it is the closest you can get to a living and breathing PHP community. A few weeks ago, I flew from London to St. Louis, Misouri, to speak at php[tek] (the PHP conference run by php[architect]). After the conference, there was a small tradition within the PHP community known as WurstCon. Essentially, hundreds of PHP conference attendees cram themselves into a small hot dog shop and host a hot dog convention, often to the complete surprise of the staff there. Likewise, community nights at PHP events are the warmest and most accepting community occasions you’ll ever run into; the PHP community is surely one that other development language communities envy.
As of PHP 7, the PHP project has changed dramatically; but what I love, remains strong. The warmth you will feel at any PHP conference, the openness in the documentation, and adoption in the language. Yes, there are practices that are undoubtedly bad within PHP itself; however, think of what the PHP community has recently achieved, ranging from PHPUnit to Composer. Throughout this book, bear in mind the improvements in PHP 7, a few of which I’ll share with you. The trajectory of the project is now certainly upwards, and let’s not forget that this wasn’t always true. The PHP community has learned its lessons from the past, whilst the language maintains the flexibility to write what is bad.
This book will seek to impart strong software engineering skills to you with the focus on implementing them in PHP. At the time of publishing this book, there is a certain void and a necessity for this kind of material. This book seeks to be the lighthouse that will not only demonstrate software design theory, but also seek to impart practical information of real value to improve the quality and maintainability of the code you write. This book leaves no stone unturned throughout the software development cycle and will seek to confront the reasons as to why the majority of software projects fail whilst also addressing design, redesign, and safeguard effective code.
This book goes beyond traditional design patterns as envisaged by the Gang of Four and details the practices that passionate PHP developers need to be successful as software engineers or leads on detailed PHP projects. This book will introduce you to the core knowledge required to understand project management techniques, why the majority software development projects fail, and why you can make yours a success.
Originally, I gave thought to writing a book on PHP when Mandi Rose, who I worked with previously, suggested I put together a book on the practices I’ve learned with PHP. Needless to say, at the time that suggestion was made, the best of my career was undoubtedly ahead of me; when the opportunity actually arose to write something like this, I felt I had learned dramatically more as time progressed. By no means should you see this book as the be-all and end-all of PHP practices; instead, you should use it to increase your knowledge base on PHP, but by no means limit it to this. In this book, I aim to give something, however small, back to the PHP community; after reading this book, I would encourage you to get stuck in and share what you’ve learned with others.
Later in this book, I will advocate Extreme Programming as a methodology and courage as a key value of this methodology. I will ask you to bear in mind the explanation of courage in The Values of Extreme Programming: “We will tell the truth about progress and estimates. We don't document excuses for failure because we plan to succeed. We don't fear anything because no one ever works alone. We will adapt to changes whenever they happen.” This is, of course, some key advice we should all follow and seek to genuinely understand risks instead of cowering behind them. For many of us, the code we write during parts of our career is the highest expression of our labor. Indeed, the late nights turning into early mornings we spend debugging and developing are what ultimately allow us to demonstrate the fruits of our labor. In essence, as software engineers, the code we write defines who we are, as such we should be open to constantly refining and refactoring our processes, which is what this book aims to support you in doing. I am incredibly honored that you chose to allow me to help you to reach this end.
Chapter 1, Why "Good PHP Developer" Isn't an Oxymoron, introduces the concept of design patterns as recurring solutions to commonly arising problems.
Chapter 2, Anti-Patterns, introduces how patterns can lead to decidedly negative consequences.
Chapter 3, Creational Design Patterns, discusses Gang of Four design patterns, namely those surrounding object creation.
Chapter 4, Structural Design Patterns, covers how multiple classes and objects can be combined to deliver a clearer interface.
Chapter 5, Behavioral Design Patterns, explains how to increase the flexibility of communication between objects by identifying patterns that can help with communication between them.
Chapter 6, Architectural Patterns, revolves around resolving common issues related to the architecture of a web application/system, potentially outside the code base itself.
Chapter 7, Refactoring, shows how to redesign code that has already been written to improve maintainability.
Chapter 8, How to Write Better Code, covers a range of concepts that haven’t been discussed elsewhere, and it also concludes with some advice for developers.
An installation of PHP 7 will serve you well throughout this book. You should be prepared to alter your development environment as needed throughout this book; we will address the installation of various tools as we encounter them.
This book is not for the despairingly hostile or those who are passively antagonistic to approaching new software engineering principles. It is not for those who seek to be lone warriors, either. When altering a given code base, you must seek to improve the code of the entire code base and everyone who works on it. You must be willing to take personal responsibility of the code you write and not blame external factors. Code maintainability cannot be improved unilaterally on shared code bases; you must write your code with the intention of maintaining code quality for those who maintain it after you. Additionally, seek to go into this book with the mindset of being able to share what you’ve learned, whether it is with those in your teams, your user groups, or the larger PHP community. In other words, approach this book with the end in mind; approach this book with the stated aim of improving your code and those in the code base you maintain.
This book is certainly aimed at the PHP developer looking to learn about the complete set of skills needed to be a software engineer, in particular, some lessons from software design; this book will seek to educate you on how your code can be made more extensible and easier to develop on. This book seeks to take your code beyond just being a bag of functions and classes, instead preferring well-designed, well-written, and well-tested code.
You will need a working knowledge of PHP and enough to build an application, but by no means do you have to be a total expert at everything in PHP; a working knowledge of the basics of software engineering will certainly give you a heads up.
You must encounter this book with an open mind and a willingness to have your preconceptions about software development challenged. This book will confront some truths about how you may be failing personally as a developer; it is vital that you approach this book with a willingness to take these principles onboard.
This book presents a set of software development patterns and principles that you can adopt. It is vital that you understand where these patterns should and shouldn’t be applied; this will be explained throughout the book, especially in the last chapter.
A key tenet of reading this book is understanding what PHP is for and what it isn’t. I expect you to enter this book understanding what problems you expect PHP to solve and what you expect to use other software development languages to solve.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-PHP-Design-Patterns/. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
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:
When it comes to coding style, I would like to introduce you to the PSR standards created by the PHP Framework Interop Group. Namely, the two standards that apply to coding standards are PSR-1 (Basic Coding Style) and PSR-2 (Coding Style Guide). In addition to this, there are PSR standards that cover additional areas, for example, as of today; the PSR-4 standard is the most up-to-date autoloading standard published by the group. You can find out more about the standards at http://www.php-fig.org/.
Coding style being used to enforce consistency throughout a code base is something I strongly believe in. It does make a difference to your code readability throughout a project. It is especially important when you are starting a project (chances are you may be reading this book to find out how to do that right) as your coding style determines the style the developers following you in working on this project will adopt. Using a global standard such as PSR-1 or PSR-2 means that developers can easily switch between projects without having to reconfigure their code style in their IDE. Good code style can make formatting errors easier to spot. Needless to say that coding styles will develop as time progresses, to date I elect to work with the PSR standards.
I am a strong believer in the phrase: always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. It isn't known who wrote this phrase originally, but it's widely thought that it could have been John Woods or potentially Martin Golding.
I would strongly recommend familiarizing yourself with these standards before proceeding in this book.
