php brilliance_ advanced coding

Upload: hanguilherme

Post on 01-Mar-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    1/361

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    2/361

    PHPBrilliance

    AdvancedCodingMojo

    ThunderRaven-Stoker

    2014 - 2016 Thunder Raven-Stoker

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    3/361

    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 tosearch for this hashtag on Twitter:

    https://twitter.com/search?q=#phpbrilliance

    https://twitter.com/search?q=%23phpbrilliancehttps://twitter.com/search?q=%23phpbrilliancehttp://twitter.com/
  • 7/25/2019 PHP Brilliance_ Advanced Coding

    4/361

    I would like to dedicate this book to the loving memory of my Father, a man who wasvery much an engineer in the traditional sense. He was also a man who enjoyedribbing me with the idea that a programmer doesnt make owt! He just pushesbuttons all day.

    This ones for you, Dad, with all its incumbent button-pushing.

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    5/361

    Contents

    The bit at the front . . . . . . . . . . . . . . . . . . . . . . . iPreface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii

    Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

    Prelude . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2More Pub Time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

    Foundations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Object 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

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    6/361

    CONTENTS

    Extending our Object Oriented brain . . . . . 128Progressive 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 . . . . . . . . . . . . . . . . . . . . 207Building on bedrock. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208

    Ghostbusters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210

    Favour Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219

    And favour Composition too. . . . . . . . . . . . . . . . . . . . . . . . . . 223

    Tell, Dont Ask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

    Instantiaphobia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259

    Do shoot the messenger . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279

    Dont Talk To Strangers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285

    Talking Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295

    Brain Check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    7/361

    CONTENTS

    Moving on to SOLIDs . . . . . . . . . . . . . . . . . . . . . 308Introducing 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 . . . . . . . . . 318Introducing 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

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    8/361

    CONTENTS

    DONT PANIC! . . . . . . . . . . . . . . . . . . . . . . . . . . . 326

    Appendices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327PHP7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328

    Up next.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    9/361

    The bit at the front

    i

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    10/361

    PrefaceThank you for picking up this book. Our journey starts here, just you and me. Wellbe navigating sections and paragraphs, following a treacherous trail. Some have gonebefore and sadly havent succeeded in reaching the final destination. But you, theressomething different about you. Im not sure what it is yet, but once weve embarkedon this journey together, Im sure Ill be able to put my finger on it.

    Lets go.

    Who this book is for.

    In a nutshell, Im pitching this book at good developers who are keen to shine, todevelop an almost supernatural ability to foresee and avoid future bug scenarios, tobe awesome. To be brilliant.

    This isnt a beginners guide to PHP, nor is it intended to be a book for mid-level

    developers either. The intended audience that Im writing for is one that mainlycomprises developers at the Seniorend of the scale, though I will freely admit that thetermSenior Developermeans wildly different things to different people and acrossdifferent organisations.

    As such then Im attempting to gear the content towards an anticipated reader who isalready familiar with the language and has been using it in an object oriented fashionfor a number of years. How many years? Again, this is an exceedingly difficultthing to quantify. One developer who has spent five years only repeatedly installingWordPress and has not engaged in any personal study wont be as far along the

    curve as another developer who has spent the last six months dedicating themselvesto 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 orcommercial-like experience already under your belt. Quite likely, youll have triedand tested a few of the MVC frameworks that litter the PHP landscape, perhaps evenhave settled on one as being your personal favourite.

    ii

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    11/361

    Preface iii

    Youll know some of the mantras and perhaps even fervently follow them; alwaysprogramming to an interface and favouring composition are certainly two qualitiesfirmly embedded in the mind of a developer that exhibits PHP Brilliance.

    In other words, this book is for you if youre the kind of developer that left the basicsbehind a good while ago, having developed a certain fluency with the language andgenerally only tend to consult the PHP manual when you need to remind yourselfwhether itsneedle then haystackor haystack then needle.

    Why did I write this book?

    Now thats a very good question and one that comes with a significant number of

    answers. Thats not me hedging, by the way, there were, and still are, several keymotivators behind my taking up this potentially insane project. Ill set them out belowbut please do bear in mind that the order is arbitrary - each one carries pretty muchthe same weight as do all of the others.

    Theres a massive clue to my first motivator in the preceding section.What on earthis a Senior Developer anyway?. The term has an exceedingly fluid definition and inlarge part, is highly subjective. A Senior Developer in Company A may only haveachieved that rank through time served, whereas a Senior Developer in Company

    B has gotten there through a demonstrable ability with the language. Even so, theSenior 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 CTOheading up the tech team. Irrespective of the scale of ranks that individual companiesapply to their teams, its certainly the case here in the UK that recruiters have muchlower standards for who gets put forward for Senior roles. At one point, you onlyneeded to put MVC and Zend on your curriculum vitae / resume in order to getsubmitted as a candidate for a senior dev position.

    Now dont get me wrong, Im not suggesting that this book is going to be the newyardstick for what a senior developer is or isnt. I might be ambitious but perhaps notthatambitious about what can be achieved with this body of work. What I am aimingfor though, with regard to this particular motivator, is a way to find a common baseforwhat I believea senior developer ought to know.

    Another motivator if you like, is perhaps more of a reaction to the sheer volumeof poor quality resources that are available online, in books and even through some

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    12/361

    Preface iv

    educational institutions. This is a quiet rebellion! It pains me to think that a newcomerto our wonderful community of PHP developers can go online, search for tutorialson 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 conspiracytheories about search engines and their page rank algorithms, no-one is yet curatingthe internet and whilst that is so, there does seem to be some value in collating thegood 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 rightinformation. This is great, but they dont often include the warnings or highlight thepitfalls of the very things that theyre teaching you about. Whilst they tell you what

    you can do, they dont always tell you whether you should. They certainly dontalways include the pitfalls and gotchas and things to avoid on this topic or that.

    This is intentionally a key feature of the book thats unfolding before you; I want tohighlight those very pitfalls and problems that can crop up in each particular topicrather than just tell you that you can do this or your can do that. A case in pointcomes early on with the chapter on Abstraction. There are certainly no shortage oftutorials that will tell you that abstraction promotes code reuse, helps avoid codeduplication. This is wrong but Ill save the explanation for the relevant chapter. So in

    some regards, you might consider this book to be a way to encourage the unlearningof bad habits that many of us have picked up along the way as well as a way tohighlight the good stuff.

    Lastly, theres an ulterior motive here, an almost selfish reason for this book. Over thelast few years, Ive picked over hundreds and hundreds of CVs, examined thousandsof lines of sample code and spent hours upon hours interviewing candidates forvarious positions on the projects that Ive had a hand in. What a dream it wouldbe were those candidates able to discuss this book with me in an interview. What do

    they agree with? What dont they agree with? Why not? I know I said that I didntintend for this book to be a yardstick for what a senior developer is or isnt, but itcertainly could be one that would helpmegauge what sort of level a candidate is at,irrespective of any superlatives that the recruiter might have used when embarkingon a drive to find new talent.

    With all of this in mind

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    13/361

    Preface v

    What is this book about?

    In a word, brilliance. PHP Brilliance is a meta-yardstick that Ive come to use myself.

    I say meta- since experience tells me its going to be a moving target. Five yearsago, it would have featured the MVC design pattern quite strongly. Now, the worldof PHP MVC frameworks has matured to the point that its standing on the thresholdof 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 certainstandard of programming knowledge as it applies to the PHP developer today. In itsscope, 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 variousarchitectural considerations and it examines and extols good working practices.

    Publishing, the leanpub way.

    Im a big fan of the lean process model. Im sure that much will be come apparentwhen we get into the good practices section of the book and I love what those goodfolks over at leanpub.com have done to take the concept and apply it to the processof publishing a book.

    If youre not familiar with the lean publishing manifesto, as put out by lean pub.com,Im 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, Ive either applied or am intending toapply many software development processes to reach the final goal of a finishedbook.

    To begin with, at the time of writing Ive completed the entire first draft of what Ithink should be in this book. This isnt lean, which would naturally abhor such waste.

    https://leanpub.com/manifesto

    https://leanpub.com/manifestohttps://leanpub.com/manifesto
  • 7/25/2019 PHP Brilliance_ Advanced Coding

    14/361

    Preface vi

    This is waterfall, a process that should bring most developers out in hives. To avoidembarrassing acts of self-flagellation, Im going to term this process marshallingtogether all of my anticipated source materials. Its my excuse and Im 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 humanpopulation will want to read. Publishers buy into this idea (hopefully!). The finishedmanuscript, guided by an editor, is sent to proof-readers, reviewers and technicaleditors before being sent to the printers. Hopefully during this time, the marketingand sales machine has been fired up in order to drum up interest before the variousdistribution channels get fed the stock that theyve hopefully been eagerly awaiting.Theres 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 endof March 2015, the first instalment will be out and available to buy. At this point, Ishall start a sprint like structure where I shall undertake to release updated versionsof the book every two weeks. Im not really adopting sprints though; I not even sureI could persuade my cats to partake in a daily standup no matter how many treats Iattempt 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 ofthe bargain. Anyone buying into the publishing of this book will be paying for thecompleted book before the completed book is done. Through the adoption of a twoweek sprint cycle, Im hoping to build confidence in the iterative process of addingvalue to this particular product.

    Lean processes are all about delivering value and eliminating waste. Lean is a cyclicalprocess and where it wins out over Waterfall is the feedback stage. Lean activelyencourages feedback from the earliest development stages in order to direct the futureprogress towards delivering the most value for the end user, whilst simultaneouslyeliminating as much waste as possible. Traditional publishing gives you the finishedproduct and then collects feedback, at which point the feedback comes too late toguide the content of the product. Lean publishing allows the end user to influenceand 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

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    15/361

    Preface vii

    with details of what you think is good, what you think is bad, what you think ismissing, that would just be so many kinds of awesome. More detail here, less detailthere, dial back on the jokes for pitys sake.

    If you have the time and inclination to get involved in the feedback stage ofthe lean process, I would love to hear from you. You can write to me here:[email protected], ideally putting PHPBrilliance in the subject line so thatI can filter effectively.

    If youre not able to get in on the feedback cycle, well then I hope you enjoy whatyoure 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 ageof 12 (so now you know how old I am!) though I would be hard-pressed to call thatprogramming since it was written in Sinclair Basic on a 48k ZX Spectrum. Ive hada love of computers and what you can do with them ever since.

    Which in turn meshed nicely with the increasing availability and popularity of theInternet in the 90s. Sure, some of it has diminished in popularity, especially since theweb 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 Perland 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 fromPerl and Java advocates!). PHP syntax was so much more comprehensible than Perls.Results came far more quickly with PHP than with Java (you dont have to recompilea 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. Ive been doing it ever since.

    Aside from being a right tech-head, I also like my beer. And archery. My piano andmy playstation. And the vampire genre in all its wondrous and bloody glory. I lovemy cats too even though they keep trying to get in the way of my writing. And I lovethe crazy, filthy, chaotic mess that is London, which is why I live here.

    Thunder March 2015

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    16/361

    ChangelogOne of my readers pointed out to me recently that it isnt always easy to know whathas changed since the last time I pushed an update.

    As a result, Ive added this page right at the start, which links the new and updatedcontent 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

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    17/361

    Prelude

    Somebody in this camp aint what he appears to be. Right now that may be one ortwo of us. By spring, it could be all of us. - MacReady

    2

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    18/361

    More Pub TimeBefore we begin the book proper, there is a key principle that we should look atfirst. At the time of writing, it is highly unlikely that you have ever heard of thisprinciple before now. I would like to say that it comes to us as the result of some supersecret research conducted over many years by a shady, off-the-books, clandestinegovernment 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 nowleaking 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 appearswithin 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, itmight 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 timepreserved. -The More Pub Time Principle

    Im not a big fan of jingoisms though, so let us proceed to break that down intosomething that makes a great deal more sense.

    https://morepubtime.com

    3

    https://morepubtime.com/https://morepubtime.com/
  • 7/25/2019 PHP Brilliance_ Advanced Coding

    19/361

    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 theirhead, then it should naturally follow that the quality of their application code willbe 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 somethingof a definition for evaluating code quality itself. Fortunately for us, we can standupon the shoulders of giants and examine the work that has already been done inthis arena.

    The functional quality reflects how well a particular application serves itsintended purpose.

    The structural quality reflects on the non-functional requirements and howwell the application code supports the delivery of the applications functionalrequirements.

    Fitness for purpose, as it is commonly known, isnt something that we will be

    considering here; building an online word processor that can compete with a desktopversion will have very different functional requirements to trying to build out a socialnetwork specifically for Alaskan tropical fish enthusiasts.

    The functional quality of any given software project will be judged by criteria thatare 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 givensoftware 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 onthe face of it but this is something that we absolutely must be able to do. Our userswill rely on our applications code to deliver the functionality that they need, elsethey will stop being our users and go look elsewhere.

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    20/361

    More Pub Time 5

    The companies that we work for will rely on our applications code to be able todeliver the necessary functionality either to increase sales, reduce costs or any otherway 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 portionof code inside an application, isnt just down to how well the code responds whengiven the right data in a low stress environment - coding just for the happy path doesnot 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 howwell that code responds to errors, failures and defects. If a caching layer is downdue 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 errormessage whilst rejecting the content of that form?

    Modelling and assessing for reliability comes in many different flavours, far toomany to discuss here, but they all have a common theme: Does the application do theright thing when conditions are favourable and does it still do something acceptablewhen conditions are unfavourable?

    If the application chokes when it is fed with garbage data, if our web site falls overonce the databases connection pool becomes saturated, then our quality in terms ofreliability could be said to be very low. As we could be said to be out of a job.

    Maintainability

    Ive ranked these four quality considerations in order of importance, which is whymaintainability comes in second. Reliability is right there at the top of the list sincewe need our code to do what it is supposed to, and respond appropriately when itcant.

    However, maintainability is a most definite second on the list when considered inorder of importance and for very good reason. Whilst the other three members ofthis list express their focus on a given snapshot of the codebase, frozen in time at anygiven point, maintainability focusses on both the frozen snapshot and a time-rangedconsideration.

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    21/361

    More Pub Time 6

    This is important for a number of reasons. In an online world, and especially in anonline world of applications written for the web using languages such as PHP, theapplications themselves very rarely reach a state of completion.

    Unlike their counterparts in the desktop world, there isnt a point in an onlineapplications lifetime where the business declares that the product is done and itstime to get the DVDs pressed and the product on shop shelves.

    This is especially true for development teams that use agile methodologies and leanprocesses, tagging and releasing incremental changes over time in order to improvethe product offering for the targeted end user.

    This is where the time-ranged consideration comes in. Code that is maintainable iscode that is resilient to the inevitable changes that come along. It is the opposite ofcode that is brittle and/or fragile. It is code that is sufficiently malleable that it willbend and flex appropriately to accomodate the seemingly endless flood of changerequests emanating from the business team without hiccup, downtime or the loss ofthat most valuable commodity: Pub time.

    Security

    Security is perhaps the most commonly misunderstood aspect of software quality.Naturally as developers we are keen to protect our applications data from the moremalicious elements of the outside world but security has a much broader sphere ofinfluence beyond the common, though no less critical, act of guarding against knownattack vectors.

    As far as security is concerned, it becomes necessary to consider the topic in muchbroader terms. One thing that is common to all applications is that they collect,manipulate and store data. It doesnt matter whether its a game, a social network, acorporate intranet or a blogging site, its the data that is king in every case.

    As far as the security aspect of software quality is concerned then, we must widenthe definition beyond preventing hack attacks to one that recognises the preservationof data integrity is paramount.

    If the data within our application is mostly ok then were in trouble since thatimplies that some of it is bad. We need all of the data in our application to be gooddata at all times, we need it be where it is supposed to be and not end up in placeswhere its not supposed to be.

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    22/361

    More Pub Time 7

    As a result, assessing the security aspect of software quality entails a lot more thanmaking sure we are protecting ourselves against SQL injection attacks, or hashinguser passwords properly. It entails making sure we have the right kind of validation

    in place and that weve put that validation code in the right location. It entails makingsure that a multi-stage data manipulation process can be rolled back to its originalstate should one of those stages fail. It entails a lot of things but the final outcomeneeds to be this: All of the right data in all of the right places and none of it anywhereelse.

    Making sure that were ready for the user that has ;DROP TABLE users;@hotmail.comas an email address is one thing, but if a member of our team creates an algorithmthat accidentally sets every users first name to the four character string John then

    were already sailing down crap creek anyway and the paddle is nowhere to be seen.

    Efficiency

    Ive known developers in the past who have placed an inordinately high degree ofimportance on creating highly efficient, fast running, low memory usage code. Onesthat have declared code can only be beautiful when its fast.

    Thankfully, most of us already know better.

    In the days, months and years before the explosion of cloud computing and virtualisa-tion, the performance of an application could often be improved by an activity knownas throwing more tin at it. Adding another server to the rack or installing fast harddisks or more RAM was commonly cheaper than paying a developers salary for thetime required to optimise inefficient code.

    Nowadays, we can still throw more tin at it but in a virtual sense by spinning upanother instance.

    Nevertheless, creating code that is performant and efficient is still very important if

    we hope to preserve our all-important pub time. Code that is already reliable, secureand maintainable can always be optimised for speed and efficiency.

    But code that is written for speed first can rarely be optimised for reliability, securityand maintainability after the fact.

    Thats not to say that speed and efficiency arent important of course. An onlineapplication that takes thirty-seven minutes to turn a request into a response had

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    23/361

    More Pub Time 8

    better be delivering absolutely critical information at the end of the cycle if it haseven the slightest hope of retaining users.

    The reality for the vast majority of online applications is that the request-responsecycle needs to complete in a matter of seconds, not minutes. Fortunately for us inthe online world, there are a number of techniques that we can employ in order toimprove theperceivedperformance of an application and therefore improve the userexperience.

    Rather than despatching that account activation email as part of the sign-up proce-dure, we can queue it for an independent process such as a cron or a daemon to takecare of.

    Rather than parsing and processing an uploaded CSV as part of the request-responsecycle, we can move the file to a watched directory and allow the status of thefiles processing to be reported back to the front end by a series of subsequent,asynchronous calls.

    Of course, we can optimise the actual performance and efficiency of our applicationcode and not just the perceived performance and efficiency. The developer thatperforms a SELECT * FROM users and then loops through the entire recordset inmemory just to find the row for the user that has just logged in probably needshis or her butt kicked first and foremost before being taught how to write a WHERE

    clause. Returning a single row in this situation is clearly much more efficient thanpulling out the entire table.

    Despite being at the bottom of this list, efficiency is still a very important factor in alist of four factors for assessing the quality of an application and its code.

    Software quality is a huge topic in its own right, with hundreds of books and

    academic papers published on the subject. Here, Ive only just scratched the

    surface and only very lightly at that. Nevertheless, I hope Ive been able to at least

    impart the vaguest impression of what is meant by quality code being reliable,maintainable, secure and efficient.

    Which brings us closer to considering what the right kind of knowledge might be.Before we do that though, we should take a moment to consider the wrong kind of

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    24/361

    More Pub Time 9

    knowledge.

    Hello World!

    The learning process is well documented. Not just in programming circles but in anykind of trade or craft, a practitioner will go through a number of distinctive phases.At the start comes the novice, picking up the fundamentals and learning the firstprinciples. It might be horribly presumptuous of me to say this but Id be preparedto wager that a great many of us began this journey by writing Hello World on thescreen, all thanks to Brian Kernighan way back in 1973.

    Advancing beyond the novice stage is the journeyman, building upon the fundamen-

    tals by acquiring additional knowledge and combining it with experience in order tohone their skills and further their personal development before readying themselvesfor the final stage, that of the master craftsman.

    Traditionally, the title of master craftsman would be bestowed upon a practitioner bythe guild that oversees their particular trade or craft. When ready, the journeymanwould prepare and submit a piece of work as part of the application process and itwould be the members of the guild who would judge said piece of work and establishwhether they deem it to be worthy or not.

    In the world of online application creation we arent so fortunate to have such astructured approach to personal development; one cannot readily apprentice oneselfto an established master craftsman. As such, our journeyman stage is less a joy-filledskip through a sun-drenched meadow and much more a stagger through a perilousswamp filled with traps and pitfalls.

    Its also huge, thanks to the Internet. The journeyman developer is literally inundatedwith opportunities to advance their knowledge and abilities thanks to the plethora ofmaterials available to him or her. There are books aplenty, there are courses to followboth online and in more traditional bricks-and-mortar learning establishments, thereare articles and blog posts that are way to numerous to count.

    Which is precisely where the danger lies; the largely unrestrained and unregulatedpublication of tutorials and training videos presents a very real danger to the journey-man coder. With such an unfathomably large volume of information available, howdoes the journeyman coder ever hope to be able to sift the good quality informationfrom the bad, especially when the bad keeps coming at an ever-increasing rate?

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    25/361

    More Pub Time 10

    As a case in point, as recently as December 2015 I encountered two exceedingly poorquality tutorials linked to in developer forums that I frequent. The first showed howto easily populate variables using the extract()function, which is a particularly

    dangerous trick to learn without making the reader fully aware of the dangersinvolved.

    However, even that pales into insignificance when compared to the second tutorial,which illustrated how to use AJAX to send search terms from an html form to a PHPbackend that would return the search results back to the front end after querying thedatabase. On the face of it, this seems an entirely reasonable thing to post a tutorialabout and as a topic, it has certainly been covered any number of times before.

    However, in this particular tutorial, the example code illustrated the creation of a

    SQL query by iterating over the $_POST superglobal and using the values directlyand without any form of validation or sanitisation.

    For any time-served developer this should be a horrifying state of affairs; that atutorial posted in 2015 pays no heed to preventing SQL injection attacks and thusproving the proverb A little knowledge is a dangerous thing.

    Yet it is easy to forget that new coders take their very first steps onto a coding careerpath every single day. Any such hapless coder copying and pasting this tutorial codeinto their own endeavours would become vulnerable to those same SQL injection

    attacks, at least until such time that they acquire the right kind of knowledge thatwould let them guard against these attacks.

    Which brings us nicely back around to considering just what does constitute theright knowledge. Regrettably, at the time of writing there isnt one definitive answerto that question. It is also rather dubious that there ever could be.

    One of the very great joys that a career in software development brings along with itis the fact that the learning process never ends. No matter how advanced a developerbecomes in their mastery of the topic, there is always more to learn. On the one hand,this is because the topic itself is so vast. On the other, it is because the technologyprogresses relentlessly.

    Complete mastery of application software development is entirely unobtainable forthese two distinct reasons. At any given moment, there is already too much to fitinto a single human brain. And todays latest technique has every chance of beingsuperseded tomorrow.

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    26/361

    More Pub Time 11

    Despite this, it is certainly my strongly held belief that there is certainly a catalogueof knowledge that every Senior Developer and above needs to have tucked undertheir belt. Such a catalogue of knowledge can cover a variety of topics, from very

    specific morsels such as always ensuring that you escape, validate and sanitise yourinputs appropriately to much broader concepts such as the key software developmentprinciples, rules, laws and even design patterns.

    But why?

    The reason itself can quite simply be stated as this; to build better software. Morespecifically, to build better software expressly in terms of its structural quality sothat it is reliable, maintainable, secure and efficient.

    Fantastic! So now that weve nailed down the definitions of software quality and theright knowledge needed to achieve software quality

    What the heck is Pub Time?

    If we are to preserve our invaluable pub time by pre-emptively learning the rightstuff in order to achieve high quality software, we need to know what the chuffingheck is pub time?

    This is the more jocular aspect ofThe More Pub Time Principle, which is preciselywhy itll never be accepted by academicians as a valid software principle but in briefit goes like this:

    Pub time is that time expended in any manner more conducive to a happier

    and more fulfilling life than staying behind in the office hunting down and

    fixing software bugs that were entirely avoidable in the first place.

    For me, that quite often entails a trip to pub with my friends to have a catch-up over

    a drink but it isnt, by definition, limited to going to the pub. Pub time can entailtaking your beloved out for a romantic meal. Or it can mean getting home in time toread bedtime stories to the little ones. Or going to watch a play. Or hitting the gymfor a workout. Or firing up your games console in order to blow the heads off of alieninvaders.

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    27/361

    More Pub Time 12

    In fact, engaging in any activity that improves the quality of your life and itsenjoyment can be considered as pub time, in comparison to late nights wastedhunting down and fixing perfectly avoidable software defects.

    Conclusion

    The journeyman stage of a software developers career is somewhat ill-defined, andthis is certainly all the more true for the developer working in the online world.

    Much of the web is built upon open source languages such as PHP, Ruby and Pythonto name but three. Each of these languages have a dedicated following and aresupported by fantastic communities and as such, there is a tremendous wealth of

    learning resources available both online and off.

    One thing that the Internet will never be able to achieve though is the elimination ofthe journeyman stage. It simply is not possible for a learner, of any craft or topic, to

    jump straight from novice to master without having spent time in the journeymanphase. This isnt a limitation of technology that might be addressed in the future, itsa limitation of the human mind. Knowledge acquisition is done through the processof learning, leaving us at the mercy of our current biological limitations.

    What we absolutely can do though is shorten the path that the journeyman takes.

    When faced with the boggy swamp that separates the land of the novice from theland of the masters, we can pick out a sure, swift and safe path to follow - one thattakes us to all the good places to visit and leads us safely past the traps and the pitfalls.

    This is entirely whatThe More Pub Time Principleaims to do in providing its rathernebulous definition:

    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.

    There are already a number of initiatives currently in play intending to helpthe journeyman developer find the faster, safer route through the quagmire. One

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    28/361

    More Pub Time 13

    rather excellent resource is thePHP: The Right Wayproject, which I would highlyrecommend to PHP developers at every level. Another resource is this book.

    The goal of PHP Brilliance as a book is to put all of the right kinds of informationin front of you. From architectural concerns such as MVC vs Service OrientedArchitecture vs Microservices to a thorough examination of the SOLID principles,from looking at abstraction and inheritance in a new light to considering thefrankenstein method of utilising closures.

    The goal of PHP Brilliance as a state of mind is to ensure that you are equipped tolead the team in creating beautiful code that is reliable, maintainable, secure andefficient.

    Life is short so please do take this advice to heart: Preserve your all-too-precious pubtime, and do enjoy the journey along the way.

    Last but by no means least please remember; drink responsibly.

    http://www.phptherightway.com/

    http://www.phptherightway.com/http://www.phptherightway.com/
  • 7/25/2019 PHP Brilliance_ Advanced Coding

    29/361

    Foundations

    I dunno what the hells in there, but its weird and pissed off, whatever it is. - Clark

    14

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    30/361

    Object Oriented ThinkingBefore we can get onto the really meaty stuff, its important for us to take a pause andcheck on our understanding of what object oriented programming is. Even thoughthis isnt a book for those first starting out in their development career, it becomesall to easy to form a fixed opinion of OO stuff when we first come across the idea asdevelopers.

    Further to this, theres a plethora of online tutorials that all take pretty much the

    same approach to explaining it and, as such, these tend to propagate some ratherfixed thinking in this area.

    If were going to build our palaces and castles in beautiful and elegant PHP code,we must turn our attention first to what we are intending to build upon. In order toraise glorious edifices of logical magnificence that not just blend into the world widewebs skyline but to actually be part of what defines that skyline, we must focus onthe groundwork.

    Our applications need to not only suffer the slings and arrows of outrageous fortune

    but also stand firm against the whims and change requests of our business teamsand product managers. These change requests are the earthquakes and floods thatour application development must withstand. We know that theyre going to come.We can brace ourselves effectively against the flood. Just so long as our foundationsare rock solid.

    So lets go back to the basics and examine what we already know.

    All too frequently, a tutorial will take the notion of an object as being a representationof a real world thing and how the developer is supposed to hang on to this notionas the author goes on to explain how real world things have a particular set ofcharacteristics and attributes that go on to define what the thing is and what it does.

    The benefit of this approach is that the examples given are already familiar to thereader and as such allows him or her to connect the concepts with current knowledgeand experience. Anyone setting out to learn object oriented PHP will know what acar is. Or that a dog is a type of animal. For anyone approaching object oriented

    15

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    31/361

    Object Oriented Thinking 16

    development from a procedural background, something that is certainly prevalent inthe PHP arena, this relationship between code and real-world objects can help thedeveloper reach that penny drop moment sooner; that point where he or she will

    suddenly get it.

    The danger here though, and its a pitfall that many of us have fallen into, is that thedeveloper starts to cling on to this idea of linking the objects they create with realworld examples. The next project that they take on, theyll starting hunting downthe nouns in the project brief and planning their objects around them. This hereis a User, that over there is a Product. Its a perfectly valid start to the processof identifying and designing the objects that will be the key players in our newapplication. But it is only a start. Unfortunately, that is commonly where the tutorials

    end.If youre going to be guiding and mentoring the more junior members of your team,youre going to see some quite iffy code along the way. Just to make sure that wereon the same page, so to speak, I would like to set out the path that were going totake in order to reach object oriented thinking. Its starts with a shiny new junior,a likeable chap that well call Joe. The route that Joe has taken through the PHPlearning landscape in order to arrive at our office OO ready is not an uncommonone. Id like to say that its entirely fictional but that wouldnt be quite true. You see,

    Joes path was actually the path that I took albeit with some hearty doses of artisticlicense added here and there. I have no shame.

    From the outset, Joe learnt to script in PHP; building out the pages of the sites thathe built with one script for each. Here an index.php, there anaboutus.php. Thingssuch as database access and variable assignments could be done at the top of the file,then down below the page itself is built up with html and peppered with inline phpconstructs. At the top, the program logic, at the bottom, the output.

    After a while, Joes realised that hes duplicating significant amounts of code across

    his scripts. This is the point where he starts breaking chunks out into separate files;header, footer, routines for accessing the database, others for building html tables.This of course is all in accordance with the tutorials that he has been followingregarding the use of the includeand requirefunctions.

    Before long, hes creating libraries of commonly used functions which he can portfrom one project to another. Big old PHP files with names such as database.php,

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    32/361

    Object Oriented Thinking 17

    html.phpand other such collections of useful functions gathered together in a singlefile.

    What happens then when Joe starts reading up about object oriented development?Hes introduced to a Carclass that not only has properties for things like the wheelsand the engine, but also methods (functions!) for when the car needs to do things likemove(),turn()and stop().

    Joe thinks itd be a great idea to wrap his carefully crafted library of functions inclassstatements. This now is the point where Joe could take one of two paths. Doeshe instantiate aDatabaseobject in order to use those transplanted library methods?Or does he add the statickeyword to the function declarations so that he can callthe class methods statically?

    Well, instantiating the object doesnt really look to be terribly useful. Lets go withthe static.

    Now Joes coding regularly features things like this:

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    33/361

    Object Oriented Thinking 18

    an entire process from start to finish. Perhaps the most obvious example of this isan object method, probably located in a class called User and most likely namedsomething along the lines of create or register.

    Ill grant you that for many web applications, the user registration process can be aconvoluted one, performing validation against a number of submitted form fields,creating a user record along with the login credentials, possibly also storing anaddress and linking the newly created user to it as well as hooking up any numberof configuration settings. What has happened here is that the developer has takena procedural process and simply transplanted it into an object method. What usedto live as a single php page for receiving and processing a user registration has nowbeen transplanted wholesale into a single method in theUserclass. Not a literal copy

    and paste operation you understand, but a selective extraction and remodelling of thecode to squish it in between those opening and closing braces.

    Joe starts by validating the parameters that were passed in to the register() method.If thats all fine and dandy, he moves onto performing the database ops necessary toget the data into storage and extract the ids. This part may result in just one querybeing run, or it could be many; the basic user details could be accompanied by arow of default preference settings in one table, a physical home address in another. Ifthat all proceeds ok, Joe then sends out the welcome-cum-verify email before finallyreturning atrueor falseback to the original invoker of the method.

    In just that one method, we have a minimum of three fracture points - places wherethe process can fail - leading to a brittle design that can fall over a number of waysand be difficult to maintain at the same time. The validation stage, the database stageand the email sending stage.

    Now is a good time to introduce a key principle to object oriented thinking. I dontrecall where I first encountered this one but it has stayed with me ever since. It goeslike this:An object should either know things or do things, but never both.

    So many of the applications that we build are going to have a Usermodel object. Ifsuch a model object represents what we know about a particular user, and we knowthat user registration is aprocessthen it naturally follows that ourUsermodel classcannot have aregister()method.

    The more that you think about this, the more it makes sense. After all, why shouldall of our instances of the Userclass be lugging around a method whose purpose is

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    34/361

    Object Oriented Thinking 19

    to create the user record in the first place. When would such an instance have needof theregister()method again?

    If you were to take that knows things or does thingsprinciple and apply it to the modellayer of your most recent application, how many model classes would it suggest thatyou change? How many of the entities in your model both know the details of thething that it represents (i.e. hold the data for) and provides ways to manipulate thatdata beyond the act of setting and getting it?

    In most cases, the primary residents of our model layer will be objects that representthe data that lives inside our application. In this sense, these are the objects that knowthings. For instance, suppose we have an application thats going to be handling lotsofUserinstances. We ought to be confident that each instanceknowsthe name, date

    of birth and email address of theUserthat it represents. In all likelihood, a full blownapplication will have Usermodels that hold a lot more detail than that but this willserve us as a good starting point for the time being. None of these instances shouldbe holding methods thatgo beyondmanaging the individual pieces of data that theyrepresent. The methods of our model classes should be entirely introspective. Settersand getters are naturally of this ilk but what about the methods that we can identifyas being processors?

    What do I mean by processors?

    Processors are methods that do things. A method that validates user input is aprocessor. A method that triggers the sending of an email is a processor. In almostevery case, unless a processor is specifically introspective, it can be moved out intoa new object thats designed to handle, to encapsulatethat process.

    For the registration procedure, ideally what we are looking for is a whole range ofobjects all collaborating in the user account creation process. Each object will have atightly defined area of focus, performing a single task and performing it well. Havingeach tiny piece operating as a part of the whole is our goal here. Were looking for

    a range of validator objects responsible for checking each part (a password validatorcan confirm that the offered password has the right number and range of characters,a date validator can confirm that a submitted date of birth is in the right format, andperhaps importantly, is within the correct range (over 18s only?).

    When we take this approach, were neatly separating the logic that performsvalidation away from the logic that performs record creation. Continuing in an

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    35/361

    Object Oriented Thinking 20

    ideal fashion, our process for record creation should be nicely squirrelled away andseparate from the objects that represent those data records in the first place.

    One thing that you may very well notice in this book is how often Illdraw your attention to apparently circular references. The chapter on

    inheritance refers you forward to the chapter on the Liskov Substitution

    Principle. The chapter on the Liskov Substitution Principle refers you back

    to the chapter on Inheritance and also sideways to the part on favouring

    composition over inheritance. There are so many ways in which one topic

    will either rely on or reinforce another that the boundaries start to blur.

    Wherever the crossovers occur, I will endeavour to point them out to you.

    Now that youve just read that aside (you did, didnt you?), Im going to make my firstmention of the Single Responsibility Principle. The Single Responsibility Principle is,to my mind, the absolute single most important one of the five principles that go into make up the set of SOLID principles. It also pleases me greatly that its the firstone in the set. Familiarity with the SRP can only help to reinforce the idea that ourobjects should either know things or do things, but never both. If we have objects inour system that know things and do things at the same time, its a reasonably safebet that were already violating the Single Responsibility Principle. When we get to

    that chapter, I hope to make it clear as to why this will be.

    Returning to Joe then, we know that his tutorials taught him to build his objectsbased around thenounsof his system. We also know that those self same beginnertutorials didnt tell him when to stop adding methods to his objects. The good newsis though that were now in a much better position to enlighten him as to when hesputting too much into a single class.

    Regrettably its not so easy to draw a line between the knowing and the doing.Adding processors to an object thats only supposed to be knowing things is all too

    easy to do. Worse still, it usually begins with the tiniest little thing and before youknow it, the slow but inexorable creep towards bloated classes has begun. How thenare you supposed to watch out for this, outside of an all-out code audit?

    Taking a finger in the air approach, you should start to feel uncomfortable wheneverany of the following signs appear in an object method.

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    36/361

    Object Oriented Thinking 21

    Conditional statements such as an if statement or a switch appear in a method,and those conditionals are not used in performing validation but are selectingdifferent logic paths to follow based on a incoming parameter. Try to restrict

    the use of if statements to validation only. In the event that youre creatingbranched processes in your code because of the value of a particular property,youre almost certainly going to be better served by creating an independentobject for each branched process and utilising something like the Strategypattern, or the Chain of Responsibility pattern in order to handle the processing.

    You cant see the start and end of a particular method at the same time. If asingle method occupies more than a single screenful in your editor of choice,you have a problem. Look carefully at those methods to see if you cant at least

    break them down - the chances are good that theyre doing more than one task.As a general rule of thumb, Id suggest ensuring that your methods contain nomore than twenty lines of active code.

    There are lots of comments insideyour methods. Nicely documented code is agood thing, but if you find a method that feels the need to explain every step itstaking, its either taking too many steps or the author thinks youre a numpty.The best methods are nice and short, with easy to follow code and a terse buthelpful explanation of the intent in the docblock above it.

    These are the types of things that we need to be looking out for when were reviewingthe code of our more junior team members, and indeed the code that we produceourselves. Detecting code smells is a knack that comes with both knowledge andexperience but just by being aware of these three things, youre already well onyour way. Nevertheless, code smells are certainly rife in PHP. Somehow it just seemsto be something that we in the PHP community have grown up with, although ofcourse there are plenty of examples to be found in other languages too. Even so, theyare certainly something that we need to guard against. Much of the advice in theupcoming chapters is geared towards not such much how to avoid code smells, but

    how to take the right approach to creating an application whose objects dont stink.Martin Fowler has anexcellent bliki poston code smells which succinctly explainswhat they are but in doing so he makes mention of anaemic objects that might benefitfrom having behaviours added to them. Im not in full agreement with the brevityof this post since I really am very keen to put forward the notion that any single

    http://martinfowler.com/bliki/CodeSmell.html

    http://martinfowler.com/bliki/CodeSmell.htmlhttp://martinfowler.com/bliki/CodeSmell.html
  • 7/25/2019 PHP Brilliance_ Advanced Coding

    37/361

    Object Oriented Thinking 22

    class, and the objects that are instantiated from them, should have a laser-focussedintent and purpose. If youre interested, you can find a list of the more common codesmells online, but I would actually be keen to suggest that you look them up after

    were done with the first part of the book. Reading about them afterwards is muchmore likely to reinforce what you will have already read at that point.

    Anyway, lets bring this back on topic. If we were to continue along the pathof tightening the focus of our imaginary User class, what questions should webe asking? Weve already considered the possibility of removing the register()method since weve determined that it doesnt belong within instances of our Userclass. How about password handling? This is perhaps the second most prevalentwrong thingto be found within a user model. For sure, we may want to accept and

    hold the hashed value of a users password but do we actually want to incorporatethe hashing mechanism within the user class itself?

    The immediate answer seems to be yes, since its something that well be doing onlyin conjunction with the users own data. Nevertheless, we need to consider all of thethings that we might want to do with passwords. For starters, well need to be ableto accept a password from the user when they registerfor an account, which thenneeds to be hashed appropriately. Obviously. we will also need to be able to check apassword when they log in, generating a hash of of the password that theyve givenus and checking it against the hash that weve already stored. Already, we have twoprocessors for the most basic of operations.

    Experience tells us that we are also going to have to provide some sort of passwordreset mechanism, since some of our users are likely to fall squarely into the cantremember passwords for toffee camp. Do we also need to implement a lock-outmechanism after three failed login attempts?

    Answering these questions leads us to the conclusion that actually, building passwordhandling logic into ourUserclass is maybe not such a good idea afterall. Instead, wecan wrap up all of these password related methods inside a new PasswordManagerclass, instances of which can either be injected into our Userinstances at creationtime, or lazily loaded on request dependent upon our appetite for tight/loose couplingbetween a user instance and a password management processor.

    Simply by hiving off two very common processes, that of registration and passwordmanagement, weve not only improved the focus of the Userclass dramatically, wehave also created two additional classes with tightly defined areas of responsibility.

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    38/361

    Object Oriented Thinking 23

    That in itself is as awesome as a large and tasty pint of ice cold beer. Well, maybealmost as awesome - nothing really comes close to a large and tasty pint of ice coldbeer. Ever.

    So where does this leave us now? All being well, we have progressed from the stagewhere the most basic tutorials leave off. We are now a little better equipped toguard against thinking of our primary classes as silos for the ever expanding listsof processor methods that our application appears to need.

    This is rather the key point that I want to make at this stage. All too often, its terriblyeasy to get stuck with the real world nouns idea when thinking about the objects thatwill come into play within our applications, when what we really need to develop isan ability to think of application objects in an abstract sense. There isnt a tangible

    real world equivalent for a PasswordManager but if we can successfully keep thatnotion of objects only being able to know things or do things at the forefront, werea long way down the trail of instinctively knowing what should go where.

    Summary

    For our first chapter, Ive rather concentrated on the idea of grouping our applica-tions objects into two distinct camps; the knowers and the doers. This is very much

    the key theme that I would like to introduce at this point. In a very general sense,our knowers are likely to be the principle citizens that reside in our model layer.They hold and represent the data that lies at the heart of our application. These arethe users, the products, the orders and the invoices. They present an interface whichis designed to set, retrieve, manipulate or transform the individual elements of datathat they are responsible for.

    Then there are the doers. The objects within our system that cause things to happenand whose interfaces comprise methods that we can call in order to trigger thosethings. These doers might mask the simplest of processes, such as the hashing of apassword, or they might be a facade onto much more complex procedures, governingthe various stages of user registration for example.

    Clearly then, Im really quite keen on this idea. Largely because Ive witnessed thepositive effects that it can have. Its not so much the idea in itself per se, more that theend results speak for themselves. Smaller, tighter, leaner and meaner objects are somuch more efficient and maintainable than the alternative: classes treated like silos

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    39/361

    Object Oriented Thinking 24

    into which weve dumped great quantities of superficially related methods almost asif we considered the class name to be little more than a namespace for a coagulatedlibrary of code.

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    40/361

    The Four Central TenetsIf theres one thing that developers seem to get a bit lax about when they attainthe senior developer status, its the basics. The simplest bits of object oriented PHPdevelopment. I dont know why this would be. If you take your average Joe Seniorand ask him to explain things like encapsulation or inheritance, the responses youllget tend to sound like blog post titles.And why not?They are after all, the basics ofobject oriented development anyway.

    Encapsulation? Yeah, you can do data hiding with encapsulation. Abstraction? Greatfor reusing common bits of code by moving them into a parent class.

    A core part of the problem here is that nobody really thinks about the four centraltenets of object oriented development once theyve gotten past the beginner stuff.They read it. They got it. They tried the code examples. Bang. Done. Whats next?

    This, of course, is entirely reasonable. Why should they? With a constantly evolvinglandscape and some really exciting new tech stuff just around the corner its notexactly easy to persuade your average developer to give up that article on PSR-7

    and the implications that it brings for HTTP middlewares in favour of reading aboutencapsulation all over again.

    What are you proposing? Kinda sounds like its gonna be a drag

    Indeed, I know that theres quite a hurdle ahead of me by starting a book with pro-gramming topics that are decadesold. Nevertheless, Im motivated to turn my readersinto winners because its the developers that do strengthen their understanding ofthe basics - those guys, you guys, you are the ones that will win in the end. You mightfeel tempted to go thundering ahead without doing a pre-race check but I can assureyou, those wheels are going to come off before you know it.

    Instead, the developer that takes his time over the fundamentals and the basics isthe developer that will find the middle and end stages of the race, the crucialstages,much smoother and easier. He or she will be the one to go cruising past and on tothe finishing line, whilst the other guys? Theyll be the ones bogged down in the pitlanes of bug fixing and maintenance.

    25

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    41/361

    The Four Central Tenets 26

    The four central tenets are of course encapsulation, abstraction, inheritance andpolymorphism; topics that have been around for as long as theres been objectoriented programming. Each one gets its own chapter and Ill deal with them in

    that very same order.

    We should turn the page then, and get cracking with Encapsulation, for I am surethat you are as excited at the prospect of reading about it as I have been in the writingof it. Oh yes.

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    42/361

    Encapsulating our ideas.When was the last time that you thought about Encapsulation?

    The chances are high that its been quite a while, especially if youre already livingamong the ranks of the Senior Developer. Encapsulation is the very first thing thatyou learnt about object oriented development and its hardly a topic that youll havehad cause to revisit very often.

    Despite this, Im keen for us to go over the topic again. After all, Ive harped on plentyof times already about making sure that we build upon solid foundations and to dothat, we need to get the absolute basics down pat.

    If, in the previous chapter, you silently nodded when I wrote Encapsulation? Yeahthats about data hiding then we do need to address this topic! Undoubtedly it iswith the very best of intentions that many of those tutorials that weve all beenexposed to tend to present the notions ofencapsulationanddata hiding/informationhidingas being one and the same. Regrettably, not all tutorials do this and its because

    of this, and my desire to get everyone on the same page, that we need to go over itagain.

    So what isEncapsulationthen?

    Going by a generally accepted definition, it is the bundling of data with the methodsthat operate on that data.

    See? Nothing in there at all about the hiding of anything. This should naturally gelthough with what I was proposing earlier about how theknowersin our applicationshould only be carrying those methods that are responsible for maintaining and

    manipulating the data that theknowerscarry.

    To give a super-brief example in code, something like this will illustrate the idea ofencapsulation.

    27

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    43/361

    Encapsulating our ideas. 28

    class User

    {

    public $name;

    public function setName($name)

    {

    $this->name = $name;

    }

    public function getName()

    {

    return $this->name;

    }

    }

    This is nothing but a painfully simplistic class that shows the bundling of data($name property) with the methods that operate on that data (setName() and

    getName()respectively). Not the slightest hint about hiding anything going on there,particularly when you consider that the $nameproperty and the two methods are alldeclared as being public.

    So, the guy that gives you the stock response about data hiding? Hes a bit off themark but who can possibly blame him? Even the Wikipedia page on Encapsulation

    seems to promote the very same idea. Make no mistake though, when we come tobuilding out robust, scalable and maintainable applications we do actually want tokeep the ideas of encapsulation and data hiding together.

    So what then is data hiding?

    For starters, lets get rid of that term data hiding entirely. Correctly, we need torefer to it asinformation hidinginstead, which more appropriately covers both thedata aspects and the implemented logic that operates on those data. Informationhiding is the process by which we can prevent certain data and logical aspects of our

    classes and objects from being accessible to its clients and collaborators through theuse of access modifying keywords such as private,protectedandfinal. Or to put itin a slightly different way, information hiding is all about the ability to protect theinner workings of our objects from outside interference. But what benefit is that?The answer lies in the ability to protect the integrity of our data. Nothing is moreimportant to the security of your application than this.

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    44/361

    Encapsulating our ideas. 29

    When we consider the topic of security from the perspective of an online

    application, we often concern ourselves with the issue of protecting that

    application from outside attack. We want to keep the bad guys out and

    our databases safe from evil wrongdoings. This is of course how it shouldbe but I do also want to make sure that when we talk about application

    security, we reposition our view point to that of data integrity. Data

    integrity means not only that it stays where its supposed to, that is, inside

    the storage systems that we design and implement, but also that it remains

    correct and true.

    Before we move on, let us just make sure that were clear on what this informationhiding malarkey is all about. If we look again at that super simple class above, the

    $nameproperty is clearly out in the open. Any of our other code, when it sees aninstance of this User class could happily change the value of the $name propertydirectly and indiscriminately.

    $user->name = 'Joe';

    Pretty basic stuff! We can of course prevent that sort of unrestrained data manglingby making sure that we declare the $nameproperty as being private. When we do,

    were locking it away from public view and subsequently forcing any client code toutilise whatever public interface we provide in order torequestaccess to that data.Of course, such an interface as we decide to provide will be laced with traps such asvalidation, authorisation and the like.

    There are ways of achieving direct access to an objects private properties

    but Ill save those for later andonly as cautionary tales. For the benefit of

    keeping the text flowing, I shall pretend for now that the value of a private

    property canin no waybe modified directly from the outside. Hopefully,

    youll go along with me on that one.

    So now that Ive expended a little more than a couple of pages highlighting thedifferences betweenencapsulationandinformation hidingas two indepent things,what do I want you to do next?

    Why, nothing less than put them back together again!

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    45/361

    Encapsulating our ideas. 30

    Going forward, I want us to treat encapsulation as if it was both about bundlingdata and related methods together andmaking sure that we continue to hide thereally sensitive bits. I didnt want to proceed from this point without having already

    made the distinction between raw encapsulation as it truly is and information hidingas an independentthing. Now we can all move on safe in the knowledge that fromhere on in, were going to treat encapsulation as being both encapsulation proper andinformation hiding at the same time. The idea being that those of you that started offin the encapsulation is data hiding camp and those of you that didnt are hopefullynow more aligned.

    Protecting our data

    So our goal then is to protect our data and preserve its integrity. Heres a novel idea make everything private.

    Its not quite as loopy as it sounds!

    An object that only has private properties and no publicly available means by whichthose properties can be manipulated is an object that provides the maximum securityfor its data. Remember the saying that the safest, most unhackable web server in theworld is the one thats switched off? Well, there is a direct parallel that you can drawhere - the safest object that there can be is the one with all private properties andno public methods. If all of the properties and methods of an object are private, thennothing untoward can happen to the data that it encapsulates. Of course, its not easyto imagine any kind of use case for such an object.

    But let this be the basis for your approach to designing your object. Start with theidea that there cannot be a valid reason for providing any public properties.

    One of the greatest strengths of PHP as a language is the speed at which it allowsyou to develop a working application. Indeed, much of the documentation that comeswith PHPs myriad MVC frameworks describe how to create a working applicationin under an hour. Paradoxically, this strength, this power of PHP to allow such rapidapplication development is also the languages greatest weakness. It actively promoteslaziness. The kind of laziness that is anathema to, say, a time-served Java developer.Creating high quality PHP code quite often means trying to avoid following thehappy path and investing the time in going the long way around.

    Lets look at this in greater depth.

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    46/361

    Encapsulating our ideas. 31

    Say we have a user object, the properties of which are username, email address andsome sort of credit balance. We can reasonably expect that wed want to render theseproperty values to the users browser. By far, the easiest and quickest way to do this

    would be to make those properties public and then just echo them out at the relevantpoint in our code. Lets just take a look at this in code so that we can see what Imon about.

    class User

    {

    public $username;

    public $email;

    public $balance;

    public function __construct($username, $email, $balance)

    {

    $this->username = $username;

    $this->email = $email;

    $this->balance = $balance;

    }

    }

    $u = new User('joe', '[email protected]', 12.95);...

    echo $u->username;

    This is our super quick and easy way of setting up our object and then rendering oneof our objects public property. As far as PHP is concerned, its perfectly valid codeof course. As far as reflecting PHP Brilliance by being part of a robust, secure andmaintainable enterprise grade application, its nothing like.

    So what are we to do? The first step to fixing the user object above is to declare theproperties private. This is always the right thing to do. If ours was one of those idealworlds, it wouldnt even be possible to declare object properties as being public in thefirst place. Unfortunately, our world is a little way off from being ideal, so we needto be on our guard against such fundamental mistakes. I say on our guard, but thesooner that every PHP developer starts crafting their class definitions with private

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    47/361

    Encapsulating our ideas. 32

    properties, the better. Its one of those things that ought to be less second natureandmorebasic instinct.

    Lets take a look at that change.

    class User

    {

    private $username;

    private $email;

    private $balance;

    public function __construct($username, $email, $balance)

    {$this->username = $username;

    $this->email = $email;

    $this->balance = $balance;

    }

    }

    $u = new User('joe', '[email protected]', 12.95);

    ...

    // No longer can we do this...

    echo $u->username;

    // More importantly, none of our code can do this

    $u->username = 'Rumplestiltskin';

    Ok, now were starting to look a little better. With the code above, it should at leastbe apparent that the username, email and balance properties are protected againstany external influences. The class as it stands isnt exactly usable in this state sincewe now no longer have any way to access those values but no matter what our team

    mates do to the application, as long as theyre not editing this class, theres no wayto wilfully or accidentally change these properties at run time once the instance hasbeen created.

    Brilliant.

    Weve created a super secureUserclass that isnt particularly useful but hey, at leastthose tricksy little properties are now safe and secure. Our work is far from done

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    48/361

    Encapsulating our ideas. 33

    though it is at least reasonable to expect that, even if we have no need for displayingthose properties, the balance value at least is likely to change through the regularusage of our site. More work? Yes, its only right given that we are right at the start

    of the journey. Tis a winding journey though, and with no guarantees of finding amagical ring to bind them all along the way.

    Youll get plenty of cliches along the way, mind. Heres one. Something about sprintsand marathons. Yes, its not a sprint.

    And in the spirit of the aforementioned cliche, lets take a small diversion. Ive seendevelopers time and time again implement the magic__get()and__set()methodsin order to manipulate the values of private properties in objects. Some popular PHPframeworks even support the very same approach, which to my mind is a crime most

    heinous. Not least because the very popularity of said frameworks means that a lotof PHP developers are being exposed to this approach and many of those may evencome to think that its the right way to code because Hey, even these guys are doingit.

    Lets look at that in code so that we can better see whats going on.

    // error handling and validation omitted for readability

    class User

    {

    private $data = array();

    public function __set($key, $value)

    {

    $this->data[$key] = $value;

    }

    public function __get($key)

    {

    return $this->data[$key];

    }}

    There. The developers guilt is assuaged. Hes holding the objects attributes in aprivate $data array, which is of course the right thing to do, yes? Let me ask yousomething: Why is this any different to using public properties? The answer of courseis that it is not. Sure, we can start adding logic to the __get()and __set()methods

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    49/361

    Encapsulating our ideas. 34

    to tighten things up though wed certainly be fooling ourselves if we thought wewere actually improving our code by doing this. This should become more apparentas we get further along thePHP Brilliancetrail.

    Have you seen the TV SeriesLost? Jack, Kate, Sawyer, Locke et al stuckon a mysterious island after a plane crash. The first, second and thirdseasons of the show make a great deal more sense the second timearound. Once you know the ending, the beginning has so many more ofthoseA-ha!moments that make the second sitting enjoyable for reasonsdifferent to your first run through. Unavoidably, this book is going to bea bit like that. Admittedly, with fewer polar bears.

    To be fair, theres no real harm in using the magic __get()method like this purelyfrom the perspective of its own operation as long as the method itself does implementsome kind of error handling for non-existent keys in the data array.

    On its own, the __get() method does nothing but yield up values. However,its presence unavoidably lowers the resulting quality of our software, if only bymaking the merest suggestion that it should also be permissable to implement thecorresponding__set(). The very first moment that you introduce__set()into yourapplications codebase is the very first moment that you open a huge can of worms

    and you had better be prepared to cook em and eat em and swallow em down as itwill not be very long that the bugs come marching after should you happen to leaveany dangling.

    When you use the __set() method simply to modify an objects property values,youre effectively wasting your time by coding the thing up. Just set the propertiesto public and be done with it!

    Of course, Im not actually advocating that particular course of action. Quite oftenyoull see the __set() method get fleshed out with code and logic of varyingcomplexities. This might seem like a wise and clever thing to do but lets face it,every time a change request comes in that calls for this logic to be modified, theopportunity to introduce bugs into the application comes right along with it.

    Personally, Id like to strike __set()from the language itself as I dont believe anygood can come of its most common usage. When you have at your fingertips thepower to control the setting of each element of data by creating your own specific

  • 7/25/2019 PHP Brilliance_ Advanced Coding

    50/361

    Encapsulating our ideas. 35

    and dedicated method for the purpose, the use of the__set()method is naught buta shortcut. In taking that shortcut, youre effectively declaring that this one methodwill suffice for all possible current andfutureneeds for setting data within this object.

    Thats when a change request will pop up that doesnt quite fit the bill and you findyourself saying Heck, Ill just pop a little if()statement in there to handle this onecase

    Those two magic methods are here to stay though, at least for the foreseeable future.Id advise that you treat them with extreme caution, almost as if they were a pair ofsnakes. Hold them at arms length. By the neck. Whilst wearing some very sturdysnakeproof gloves. Or in other words, Id settle for it being a rule of thumb that thispair of magic methods only ever be used in very clearly defined sets of circumstances

    that are appropriate to the application in question. And by circumstances, I dontmeanits just quicker to do it this way.

    Ok, diversion taken. Lets press on. If you recall, wed gotten ourselves to the stagewhere the username, email and balance properties of our User class were declared asprivate and that these values were passed in via the constructor. As far as the rest ofour application code is concerned, those properties dont even exist. Theyre hidden.Invisible. But what good is that? And how on earth do we use those properties inour application. There are clearly situations that are going to arise where we need todisplay the username