Statistics
3
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-03-19

AuthorThunder Raven-Stoker

This book is packed with all of the key advice that you need to help you become a top tier PHP developer. It's based on years of development experience and features in-depth discussions of the essential software development topics that you need to master in order to create reliable, efficient and bug resistant code. It is the essential guide to help you exhibit PHP Brilliance. What's in it? Page after page, we'll take a look at all of the core ideas that will help a developer shine and stand out from the crowd. We'll reconsider the fundamentals and how they mesh with popular programming principles. We'll take a look at some of the more recent additions to the language and how we can leverage them effectively. We'll also examine common coding pitfalls to avoid along the way. There's a hearty section that delves in the SOLID principles, pulls them apart and examines how they apply to building enterprise grade applications. There's also quite a few ideas of my own in there for us to look at and think about.

Tags
No tags
Publish Year: 2016
Language: 英文
Pages: 362
File Format: PDF
File Size: 1.9 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)
PHP Brilliance Advanced Coding Mojo Thunder Raven-Stoker © 2014 - 2016 Thunder Raven-Stoker
Tweet This Book! Please help Thunder Raven-Stoker by spreading the word about this book on Twitter! The suggested hashtag for this book is #phpbrilliance. Find out what other people are saying about the book by clicking on this link to search for this hashtag on Twitter: https://twitter.com/search?q=#phpbrilliance
I would like to dedicate this book to the loving memory of my Father, a man who was very much an engineer in the traditional sense. He was also a man who enjoyed ribbing me with the idea that “a programmer doesn’t make owt! He just pushes buttons all day.” This one’s for you, Dad, with all its incumbent button-pushing.
Contents The bit at the front . . . . . . . . . . . . . . . . . . . . . . . i Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Prelude . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 More Pub Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Foundations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Object Oriented Thinking . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 The Four Central Tenets . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Encapsulating our ideas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Code, but in the abstract sense. . . . . . . . . . . . . . . . . . . . . . . . . 51 Inheriting vast wealth is not always good. . . . . . . . . . . . . . . . . . . 73 Prodding the polymorph. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Talking points. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Brain Check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
CONTENTS Extending our Object Oriented brain . . . . . 128 Progressive progression, objectively. . . . . . . . . . . . . . . . . . . . . . 129 More pub time through interfaces. . . . . . . . . . . . . . . . . . . . . . . 132 Putting a name on our spaces. . . . . . . . . . . . . . . . . . . . . . . . . . 147 Expressing good traits. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 Finding Closure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 Talking points. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 Brain Check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 Standing on Principles . . . . . . . . . . . . . . . . . . . . 207 Building on bedrock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 Ghostbusters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 Favour Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 And favour Composition too. . . . . . . . . . . . . . . . . . . . . . . . . . 223 Tell, Don’t Ask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 Instantiaphobia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 Do shoot the messenger . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 Don’t Talk To Strangers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 Talking Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 Brain Check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
CONTENTS Moving on to SOLIDs . . . . . . . . . . . . . . . . . . . . . 308 Introducing the SOLID principles . . . . . . . . . . . . . . . . . . . . . . . 309 Placeholders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 The Single Responsibility Principle . . . . . . . . . . . . . . . . . . . . . . 311 The Open / Closed Principle . . . . . . . . . . . . . . . . . . . . . . . . . . 312 The Liskov Substitution Principle . . . . . . . . . . . . . . . . . . . . . . . 313 The Interface Segregation Principle . . . . . . . . . . . . . . . . . . . . . . 314 The Dependency Inversion Principle . . . . . . . . . . . . . . . . . . . . . 315 Talking Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 Brain Check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 Applying Software Architectures . . . . . . . . . 318 Introducing Architectures . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 To MVC or not MVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 Service Oriented Architecture . . . . . . . . . . . . . . . . . . . . . . . . . 321 API Oriented Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 The Architectural Fortress . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 Talking Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 Brain Check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
CONTENTS DON’T PANIC! . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 Appendices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 PHP7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328 Up next. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
The bit at the front i
Preface Thank you for picking up this book. Our journey starts here, just you and me. We’ll be navigating sections and paragraphs, following a treacherous trail. Some have gone before and sadly haven’t succeeded in reaching the final destination. But you, there’s something different about you. I’m not sure what it is yet, but once we’ve embarked on this journey together, I’m sure I’ll be able to put my finger on it. Let’s go. Who this book is for. In a nutshell, I’m pitching this book at good developers who are keen to shine, to develop an almost supernatural ability to foresee and avoid future bug scenarios, to be awesome. To be brilliant. This isn’t a beginner’s guide to PHP, nor is it intended to be a book for mid-level developers either. The intended audience that I’m writing for is one that mainly comprises developers at the Senior end of the scale, though I will freely admit that the term Senior Developer means wildly different things to different people and across different organisations. As such then I’m attempting to gear the content towards an anticipated reader who is already familiar with the language and has been using it in an object oriented fashion for a number of years. How many years? Again, this is an exceedingly difficult thing to quantify. One developer who has spent five years only repeatedly installing WordPress and has not engaged in any personal study won’t be as far along the curve as another developer who has spent the last six months dedicating themselves to accreting the mastery and art of managing components via Composer. In any event the reader, that is, you, will have a certain amount of commercial or commercial-like experience already under your belt. Quite likely, you’ll have tried and tested a few of the MVC frameworks that litter the PHP landscape, perhaps even have settled on one as being your personal favourite. ii
Preface iii You’ll know some of the mantras and perhaps even fervently follow them; always programming to an interface and favouring composition are certainly two qualities firmly embedded in the mind of a developer that exhibits PHP Brilliance. In other words, this book is for you if you’re the kind of developer that left the basics behind a good while ago, having developed a certain fluency with the language and generally only tend to consult the PHP manual when you need to remind yourself whether it’s needle then haystack or haystack then needle. Why did I write this book? Now that’s a very good question and one that comes with a significant number of answers. That’s not me hedging, by the way, there were, and still are, several key motivators behindmy taking up this potentially insane project. I’ll set them out below but please do bear in mind that the order is arbitrary - each one carries pretty much the same weight as do all of the others. There’s a massive clue to my first motivator in the preceding section.What on earth is a Senior Developer anyway?. The term has an exceedingly fluid definition and in large part, is highly subjective. A Senior Developer in Company A may only have achieved that rank through time served, whereas a Senior Developer in Company B has gotten there through a demonstrable ability with the language. Even so, the Senior Developer in Company B might only be comparable in ability with a Mid- level Developer from Company C because Company C has an evil bastard of a CTO heading up the tech team. Irrespective of the scale of ranks that individual companies apply to their teams, it’s certainly the case here in the UK that recruiters have much lower standards for who gets put forward for Senior roles. At one point, you only needed to put MVC and Zend on your curriculum vitae / resume in order to get submitted as a candidate for a senior dev position. Now don’t get me wrong, I’m not suggesting that this book is going to be the new yardstick for what a senior developer is or isn’t. I might be ambitious but perhaps not that ambitious about what can be achievedwith this body of work.What I am aiming for though, with regard to this particular motivator, is a way to find a common base for what I believe a senior developer ought to know. Another motivator if you like, is perhaps more of a reaction to the sheer volume of poor quality resources that are available online, in books and even through some
Preface iv educational institutions. This is a quiet rebellion! It painsme to think that a newcomer to our wonderful community of PHP developers can go online, search for tutorials on object oriented PHP and end up filling their tender, virginal noggins with all sorts of bad and in some cases, downright dangerous advice. Setting aside the conspiracy theories about search engines and their page rank algorithms, no-one is yet curating the internet and whilst that is so, there does seem to be some value in collating the good bits. Now I could just build myself a web site and link to all the good stuff but… There are a lot of very good tutorials out there on the internet. Lots of just the right information. This is great, but they don’t often include the warnings or highlight the pitfalls of the very things that they’re teaching you about. Whilst they tell you what you can do, they don’t always tell you whether you should. They certainly don’t always include the pitfalls and gotchas and things to avoid on this topic or that. This is intentionally a key feature of the book that’s unfolding before you; I want to highlight those very pitfalls and problems that can crop up in each particular topic rather than just tell you that you can do this or your can do that. A case in point comes early on with the chapter on Abstraction. There are certainly no shortage of tutorials that will tell you that abstraction promotes code reuse, helps avoid code duplication. This is wrong but I’ll save the explanation for the relevant chapter. So in some regards, you might consider this book to be a way to encourage the unlearning of bad habits that many of us have picked up along the way as well as a way to highlight the good stuff. Lastly, there’s an ulterior motive here, an almost selfish reason for this book. Over the last few years, I’ve picked over hundreds and hundreds of CVs, examined thousands of lines of sample code and spent hours upon hours interviewing candidates for various positions on the projects that I’ve had a hand in. What a dream it would be were those candidates able to discuss this book with me in an interview. What do they agree with? What don’t they agree with? Why not? I know I said that I didn’t intend for this book to be a yardstick for what a senior developer is or isn’t, but it certainly could be one that would helpme gauge what sort of level a candidate is at, irrespective of any superlatives that the recruiter might have used when embarking on a drive to find new talent. With all of this in mind…
Preface v What is this book about? In a word, brilliance. PHP Brilliance is a meta-yardstick that I’ve come to use myself. I say “meta-“ since experience tells me it’s going to be a moving target. Five years ago, it would have featured the MVC design pattern quite strongly. Now, the world of PHPMVC frameworks has matured to the point that it’s standing on the threshold of its twilight years. In five years time, such frameworks may not even be mentioned, except in the historical sense. PHP Brilliance then is something that I have grown to consider to be a certain standard of programming knowledge as it applies to the PHP developer today. In its scope, it takes in the core fundamentals of object oriented programming in PHP. It spans numerous principles and methodologies. It covers the pros and cons of various architectural considerations and it examines and extols good working practices. Publishing, the leanpub way. I’m a big fan of the lean process model. I’m sure that much will be come apparent when we get into the good practices section of the book and I love what those good folks over at leanpub.com have done to take the concept and apply it to the process of publishing a book. If you’re not familiar with the lean publishingmanifesto¹, as put out by lean pub.com, I’m quoting it here. Please do visit the web site for a more fulsome explanation. Lean Publishing is the act of publishing an in-progress book using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do. Ironically, and maybe even hypocritically, I’ve either applied or am intending to apply many software development processes to reach the final goal of a finished book. To begin with, at the time of writing I’ve completed the entire first draft of what I think should be in this book. This isn’t lean, which would naturally abhor suchwaste. ¹https://leanpub.com/manifesto
Preface vi This is waterfall, a process that should bring most developers out in hives. To avoid embarrassing acts of self-flagellation, I’m going to term this process “marshalling together all of my anticipated source materials”. It’s my excuse and I’m sticking to it. Traditionally, of course, book publishing has been entirely a waterfall-like process. Authors dream up a project that they hope at least some portion of the human population will want to read. Publishers buy into this idea (hopefully!). The finished manuscript, guided by an editor, is sent to proof-readers, reviewers and technical editors before being sent to the printers. Hopefully during this time, the marketing and sales machine has been fired up in order to drum up interest before the various distribution channels get fed the stock that they’ve hopefully been eagerly awaiting. There’s a huge disconnect between the original proposal and the final product, which can be anywhere between 6 to 12 months and more. For PHP Brilliance, the next step is the first step towards publishing. Before the end of March 2015, the first instalment will be out and available to buy. At this point, I shall start a sprint like structure where I shall undertake to release updated versions of the book every two weeks. I’m not really adopting sprints though; I not even sure I could persuade my cats to partake in a daily standup no matter how many treats I attempt to bribe them with. The two-weekly iterations are, for me, a small way to apply discipline to the process of editing, revising and releasing the book and a big way for me to put up my side of the bargain. Anyone buying into the publishing of this book will be paying for the completed book before the completed book is done. Through the adoption of a two week sprint cycle, I’m hoping to build confidence in the iterative process of adding value to this particular product. Lean processes are all about delivering value and eliminating waste. Lean is a cyclical process and where it wins out over Waterfall is the feedback stage. Lean actively encourages feedback from the earliest development stages in order to direct the future progress towards delivering the most value for the end user, whilst simultaneously eliminating as much waste as possible. Traditional publishing gives you the finished product and then collects feedback, at which point the feedback comes too late to guide the content of the product. Lean publishing allows the end user to influence and direct what the final product becomes. This is where you come in. I absolutely, definitely, passionately want your feedback. Your reviews, your comments and especially your criticisms. If you can write to me
Preface vii with details of what you think is good, what you think is bad, what you think is missing, that would just be so many kinds of awesome. More detail here, less detail there, dial back on the jokes for pity’s sake. If you have the time and inclination to get involved in the feedback stage of the lean process, I would love to hear from you. You can write to me here: feedback@vanqard.com, ideally putting “PHPBrilliance” in the subject line so that I can filter effectively. If you’re not able to get in on the feedback cycle, well then I hope you enjoy what you’re about to read and find the content to be helpful and valuable. Who does this guy think he is? For starters, I love programming. I wrote my first “program” back in 1983 at the age of 12 (so now you know how old I am!) though I would be hard-pressed to call that programming since it was written in Sinclair Basic on a 48k ZX Spectrum. I’ve had a love of computers and what you can do with them ever since. Which in turn meshed nicely with the increasing availability and popularity of the Internet in the 90s. Sure, some of it has diminished in popularity, especially since the web arrived to send things like WAIS and gopher scurrying back into the dusty halls of academia. Like many at this time, I learnt to develop web applications using Perl and the CGI. Then PHP 3.x arrived on the scene in 1998 and that kinda changed everything. Already fluent in Java and Perl at that time, I switched (cue tears of misery from Perl and Java advocates!). PHP syntax was somuchmore comprehensible than Perl’s. Results came far more quickly with PHP than with Java (you don’t have to recompile a PHP application after fixing a typo). It was at that point that web application development became a career choice as well as a hobby. Just in time to catch the first dot com boom. I’ve been doing it ever since. Aside from being a right tech-head, I also like my beer. And archery. My piano and my playstation. And the vampire genre in all its wondrous and bloody glory. I love my cats too even though they keep trying to get in the way of my writing. And I love the crazy, filthy, chaotic mess that is London, which is why I live here. Thunder March 2015
Changelog One of my readers pointed out to me recently that it isn’t always easy to know what has changed since the last time I pushed an update. As a result, I’ve added this page right at the start, which links the new and updated content since the last release. I hope it helps! • Jan 22nd 2016 – Updated content * Part One Brain Check * Part Two Brain Check * Part Three Talking Points * Part Three Brain Check 1
Prelude “Somebody in this camp ain’t what he appears to be. Right now that may be one or two of us. By spring, it could be all of us.” - MacReady 2
More Pub Time Before we begin the book proper, there is a key principle that we should look at first. At the time of writing, it is highly unlikely that you have ever heard of this principle before now. I would like to say that it comes to us as the result of some super secret research conducted over many years by a shady, off-the-books, clandestine government agency and that it somehow fell into my hands. I would very much like to say that, in the interest of the greater good, I am now leaking the details of that principle into the public domain so that it might be read, understood and digested for the benefit of all mankind. I can do no such things though. Sadly, the reality of the situation is much more mundane. I made it up, specifically to act as the unifying theme for the content that appears within these pages. Introducing the “More Pub Time” principle If I were to express the principle in a manner that is both short and to the point, it might be expressed thus: By pre-emptively acquiring the right knowledge, a programmer may accelerate their own personal development towards mastery and the production of robust, high quality software applications. In turn, com- mon bug-prone scenarios may be avoided and highly valuable pub time preserved. - The More Pub Time Principle² I’m not a big fan of jingoisms though, so let us proceed to break that down into something that makes a great deal more sense. ²https://morepubtime.com 3
More Pub Time 4 What is the right kind of knowledge? The principle as stated up there leaves itself wide open to being accused of baldly stating the obviously. If a developer has all of the right kind of knowledge in their head, then it should naturally follow that the quality of their application code will be of a high standard. But what is the right kind of knowledge? To answer that question, we need to qualify a few things first, including something of a definition for evaluating code quality itself. Fortunately for us, we can stand upon the shoulders of giants and examine the work that has already been done in this arena. • The functional quality reflects how well a particular application serves its intended purpose. • The structural quality reflects on the non-functional requirements and how well the application code supports the delivery of the application’s functional requirements. Fitness for purpose, as it is commonly known, isn’t something that we will be considering here; building an online word processor that can compete with a desktop versionwill have very different functional requirements to trying to build out a social network specifically for Alaskan tropical fish enthusiasts. The functional quality of any given software project will be judged by criteria that are very specific to that project. In other words, does it do what it is supposed to. However, we certainly can examine the non-functional requirements of any given software project in order to judge the quality of the software and its constituent code. Typically, this is done by assessing four key factors. Reliability Can we trust our application code to do the right thing? It might sound a bit daft on the face of it but this is something that we absolutely must be able to do. Our users will rely on our application’s code to deliver the functionality that they need, else they will stop being our users and go look elsewhere.
More Pub Time 5 The companies that we work for will rely on our application’s code to be able to deliver the necessary functionality either to increase sales, reduce costs or any other way that might improve the bottom line. Failure to provide for this kind of reliance might result in the company going bust or us getting fired. The keyword here is failure. The reliability of an application, or an individual portion of code inside an application, isn’t just down to how well the code responds when given the right data in a low stress environment - coding just for the happy path does not provide us with the reliability that we crave! No, the reliability of a piece of code or an application as a whole comes down to how well that code responds to errors, failures and defects. If a caching layer is down due to hardware or networking issues, will our application choke and die? Or will it handle the situation gracefully? If a user provides us with garbage in an HTML form, either innocently or maliciously, does our code validate and sanitise appropriately, chucking up the right kind of error message whilst rejecting the content of that form? Modelling and assessing for reliability comes in many different flavours, far too many to discuss here, but they all have a common theme: Does the application do the right thing when conditions are favourable and does it still do something acceptable when conditions are unfavourable? If the application chokes when it is fed with garbage data, if our web site falls over once the database’s connection pool becomes saturated, then our quality in terms of reliability could be said to be very low. As we could be said to be out of a job. Maintainability I’ve ranked these four quality considerations in order of importance, which is why maintainability comes in second. Reliability is right there at the top of the list since we need our code to do what it is supposed to, and respond appropriately when it can’t. However, maintainability is a most definite second on the list when considered in order of importance and for very good reason. Whilst the other three members of this list express their focus on a given snapshot of the codebase, frozen in time at any given point, maintainability focusses on both the frozen snapshot and a time-ranged consideration.