Statistics
7
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-01-23

AuthorAdded by MJV

No description

Tags
No tags
ISBN: 1785887130
Publisher: Packt Publishing
Publish Year: 2016
Language: 英文
Pages: 267
File Format: PDF
File Size: 9.2 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
Mastering PHP Design Patterns Develop robust and reusable code using a multitude of design patterns for PHP 7 Junade Ali BIRMINGHAM - MUMBAI
Mastering PHP Design Patterns 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
Credits 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
About the Author 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.
About the Reviewer 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 h t t p : / / s w o r u p . c o m . n p /. You can reach him at sworup.shakya@gmail.com. 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.
www.PacktPub.com 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 service@packtpub.com 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. h t t p s : / / w w w . p a c k t p u b . c o m / m a p t 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. Why subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browser
Table of Contents Chapter 1: Why "Good PHP Developer" Isnt an Oxymoron 8 Coding style – the PSR standards 11 Revising object-oriented programming 11 Polymorphism 11 Traits (multiple inheritance) 16 Scalar type hints 19 Limiting debug access to private/protected properties 21 Setting up the environment with Composer 23 The Gang of Four (GoF) 26 Creational design patterns 27 Dependency injection 27 Structural design patterns 28 Behavioral design patterns 28 Architectural patterns 28 Summary 29 Chapter 2: Anti-Patterns 30 Why anti-patterns matter 31 Not invented here syndrome 34 Third-party dependencies with Composer 36 God objects 40 Environment variables in PHP source 43 Singletons (and why you should be using dependency injection) 44 Dependency injection 45 Database as IPC 45 Auto-increment database IDs 46 Cronjob imitating service 47 Software in place of architecture 47 Interface Bloat 49 Cart before the horse 51 Separation of development and operations 52 Excessive separation of development responsibilities 52 Error suppression operator 53 Blind faith 54 Sequential coupling 55
[ ii ] The big rewrite 58 Automated tests 59 Service splitting 60 Perfectly staged migrations 61 Tester-Driven Development 62 Bloated optimization 62 Analysis paralysis 63 Bikeshedding 63 Premature optimization 63 Uneducated manager syndrome 64 Wrong rocky foundations 64 Long methods 65 Magic numbers 70 Summary 70 Chapter 3: Creational Design Patterns 72 Software design process 72 Simple Factory 74 Factory Method 78 Abstract Factory pattern 82 Lazy initialization 90 Builder pattern 93 Prototype pattern 97 Summary 102 Chapter 4: Structural Design Patterns 103 Agile software architecture 104 Decorator 105 Adapter 108 Class Adapter 108 Object Adapter 110 FlyWeight 113 Composite 117 Bridge 120 Proxy pattern 123 Facade 127 Summary 130 Chapter 5: Behavioral Design Patterns 132 Personality traits for passionate programmers 133 Observer pattern (SplObserver/SplSubject) 135
[ iii ] Iterators 139 IteratorAggregate 139 Iterator 141 The many iterators of PHP 142 Generators 143 Template Method design pattern 148 Chain of Responsibility 152 Strategy design pattern 159 Specification design pattern 163 Scheduled Task pattern 167 Summary 168 Chapter 6: Architectural Patterns 170 Model-View-Controller (MVC) 170 Service-oriented architecture 172 Microservices 173 Asynchronous queueing 177 Message Queue pattern (Getting started with RabbitMQ) 177 Publish-Subscriber pattern 187 Summary 191 Chapter 7: Refactoring 192 What is refactoring? 192 Test, test, and test again 193 Code smells 194 Long methods and duplicated code 195 Large class 197 Replacing complex logical statements and switch statements with polymorphism or the Strategy Pattern 198 Duplicating code following a single control structure 200 Long Parameter List and primitive obsession 200 Indecent exposure 203 Feature envy 204 Inappropriate intimacy 206 Deeply nested statements 206 Remove assignments to parameters 207 Comments 208 Encapsulating Composite with Builder 208 Replacing hard-coded notifications with Observer 209 Replacing one/many distinctions with Composite 209
[ iv ] Separate versions with Adapters 210 What do I tell my manager? 210 Summary 211 Chapter 8: How to Write Better Code 212 Nature of a HTTP request 212 RESTful API design 231 Stateless nature 231 Versioning 231 Filtering 232 Sorting 232 Searching 232 Limiting fields 233 Returning new fields 233 When in doubt – KISS 233 Software development life cycle 234 On Scrum, and real Agility 235 You need to sack people sometimes 237 Lean project management 239 YAGNI and defering decisions 239 Monitoring 240 Tests fight legacy 241 Behavior-Driven Development 243 Summary 250 Index 252
Preface 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.
Preface [ 2 ] 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. What this book covers 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.
Preface [ 3 ] 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. What you need for this book 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. Who this book is for 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.
Preface [ 4 ] 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. Conventions In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The index.php file now yields this result". A block of code is set as follows: <?php abstract class Notifier { protected $to; public function __construct(string $to) { $this->to = $to; } abstract public function validateTo(): bool; abstract public function sendNotification(): string; }
Preface [ 5 ] Any command-line input or output is written as follows: echo $richard->hasPaws; New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "direct your web browser to your chosen web server and you should see Hello world! pop up on screen." Warnings or important notes appear in a box like this. Tips and tricks appear like this. Reader feedback 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 feedback@packtpub.com, 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. Customer support 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. Downloading the example code You can download the example code files for this book from your account at h t t p : / / w w w . p a c k t p u b . c o m. If you purchased this book elsewhere, you can visit h t t p : / / w w w . p a c k t p u b . c o m / s u p p o r t and register to have the files e-mailed directly to you.
Preface [ 6 ] You can download the code files by following these steps: Log in or register to our website using your e-mail address and password.1. Hover the mouse pointer on the SUPPORT tab at the top.2. Click on Code Downloads & Errata.3. Enter the name of the book in the Search box.4. Select the book for which you're looking to download the code files.5. Choose from the drop-down menu where you purchased this book from.6. Click on Code Download.7. 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: WinRAR / 7-Zip for Windows Zipeg / iZip / UnRarX for Mac 7-Zip / PeaZip for Linux The code bundle for the book is also hosted on GitHub at h t t p s : / / g i t h u b . c o m / P a c k t P u b l i s h i n g / M a s t e r i n g - P H P - D e s i g n - P a t t e r n s /. We also have other code bundles from our rich catalog of books and videos available at h t t p s : / / g i t h u b . c o m / P a c k t P u b l i s h i n g /. Check them out! Errata 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 h t t p : / / w w w . p a c k t p u b . c o m / s u b m i t - e r r a t a, 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.
Preface [ 7 ] To view the previously submitted errata, go to h t t p s : / / w w w . p a c k t p u b . c o m / b o o k s / c o n t e n t / s u p p o r t and enter the name of the book in the search field. The required information will appear under the Errata section. Piracy 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 copyright@packtpub.com with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content. Questions If you have a problem with any aspect of this book, you can contact us at questions@packtpub.com, and we will do our best to address the problem.
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
Why "Good PHP Developer" Isnt an Oxymoron [ 9 ] 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.