100% found this document useful (6 votes)
233 views

Instant Download (Ebook) Mastering PHP design patterns develop robust and reusable code using a multitude of design patterns for PHP 7 by Ali, Junade ISBN 9781785883422, 9781785887130, 1785883429, 1785887130 PDF All Chapters

The document provides a comprehensive overview of various ebooks available for download, primarily focusing on programming and design patterns in PHP and other languages. It highlights titles such as 'Mastering PHP Design Patterns' and 'Implementing Design Patterns in C# 11 and .NET 7', along with their respective authors and ISBNs. Additionally, it includes information about the authors and the content structure of 'Mastering PHP Design Patterns', emphasizing the importance of software engineering skills in PHP development.

Uploaded by

fredeltalaro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
233 views

Instant Download (Ebook) Mastering PHP design patterns develop robust and reusable code using a multitude of design patterns for PHP 7 by Ali, Junade ISBN 9781785883422, 9781785887130, 1785883429, 1785887130 PDF All Chapters

The document provides a comprehensive overview of various ebooks available for download, primarily focusing on programming and design patterns in PHP and other languages. It highlights titles such as 'Mastering PHP Design Patterns' and 'Implementing Design Patterns in C# 11 and .NET 7', along with their respective authors and ISBNs. Additionally, it includes information about the authors and the content structure of 'Mastering PHP Design Patterns', emphasizing the importance of software engineering skills in PHP development.

Uploaded by

fredeltalaro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Download Full Version ebook - Visit ebooknice.

com

(Ebook) Mastering PHP design patterns develop


robust and reusable code using a multitude of
design patterns for PHP 7 by Ali, Junade ISBN
9781785883422, 9781785887130, 1785883429,
1785887130
https://ebooknice.com/product/mastering-php-design-patterns-
develop-robust-and-reusable-code-using-a-multitude-of-
design-patterns-for-php-7-11419178

Click the button below to download

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason;


Viles, James ISBN 9781459699816, 9781743365571,
9781925268492, 1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) Implementing Design Patterns in C# 11 and .NET 7:


Learn how to design and develop robust and scalable
applications using design patterns - 2nd Edition by
Malavasi Cardoso, Alexandre F. ISBN 9789355517333,
https://ebooknice.com/product/implementing-design-patterns-
9355517335
in-c-11-and-net-7-learn-how-to-design-and-develop-robust-and-scalable-
applications-using-design-patterns-2nd-edition-53883082
ebooknice.com

(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena


Alfredsson, Hans Heikne, Sanna Bodemyr ISBN 9789127456600,
9127456609
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

ebooknice.com

(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT


II Success) by Peterson's ISBN 9780768906677, 0768906679

https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018

ebooknice.com
(Ebook) PHP 8 Objects, Patterns, and Practice: Mastering
OO Enhancements, Design Patterns, and Essential
Development Tools by Zandstra, Matt ISBN 9781484267905,
1484267907
https://ebooknice.com/product/php-8-objects-patterns-and-practice-
mastering-oo-enhancements-design-patterns-and-essential-development-
tools-23870240
ebooknice.com

(Ebook) Professional PHP Design Patterns by Aaron Saray


ISBN 0470496703

https://ebooknice.com/product/professional-php-design-patterns-2352188

ebooknice.com

(Ebook) MASTERING JAVASCRIPT DESIGN PATTERNS: create


scalable and reliable applications with advanced
Javascript design patterns using reliable code by Tomas
Corral Cosas ISBN 9781788627580, 178862758X
https://ebooknice.com/product/mastering-javascript-design-patterns-
create-scalable-and-reliable-applications-with-advanced-javascript-
design-patterns-using-reliable-code-9992610
ebooknice.com

(Ebook) Learning PHP design patterns by William B Sanders


ISBN 9781449344917, 1449344917

https://ebooknice.com/product/learning-php-design-patterns-4721254

ebooknice.com

(Ebook) Design Patterns in PHP and Laravel by Kelt Dockins


ISBN 9781484224502, 9781484224519, 1484224507, 1484224515

https://ebooknice.com/product/design-patterns-in-php-and-
laravel-5735694

ebooknice.com
Mastering PHP Design Patterns

Develop robust and reusable code using a multitude of


design patterns for PHP 7

Junade Ali

BIRMINGHAM - MUMBAI
Mastering PHP Design Patterns
Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its
dealers and distributors will be held liable for any damages caused or alleged to be caused
directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: September 2016

Production reference: 1230916

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-713-0
www.packtpub.com
Credits

Author Copy Editor

Junade Ali Safis Editing

Reviewer Project Coordinator

Sworup Shakya Suzanne Coutinho

Commissioning Editor Proofreader

Kunal Parikh Safis Editing

Acquisition Editor Indexer

Chaitanya Nair Tejal Daruwale Soni

Content Development Editor Production Coordinator

Nikhil Borkar Aparna Bhagat

Technical Editor Cover Work

Hussain Kanchwala Aparna Bhagat


About the Author
Junade Ali was a technical lead at some of the UK's leading digital agencies and has also
worked using PHP in mission-critical road-safety systems. He loves pushing PHP to its
innovative limits. Having started his career as a web development apprentice, he still
remains engaged in the academic computer science community.

Junade, an avid contributor to the PHP community, has also spoken at PHPTek and the
Lead Developer Conference. In addition to this, Junade was interviewed by Cal Evans for
Voices of the ElePHPant, and he has appeared on the PHP Roundtable. In this spirit, Junade
is proud of his local PHP user group: PHPWarks. Currently, Junade works at CloudFlare as
a polymath, and helps make the Internet more secure and faster.

Outside of development, Junade has an interest in law and political campaigns and is a
published author on constitutional law.
About the Reviewer
Sworup Shakya has worked as a web developer for more than ten years. He started his
career as a Flash ActionScript developer, before moving on to ASP.NET MVC, and finally to
PHP. During his time as a developer, Sworup worked extensively with frameworks, be it
ASP.NET MVC or AngularJS or Laravel. However, while he was working as an
ActionScript developer, he had to create one, which gave him knowledge of design patterns
and OOP concepts that has helped him improve in order to be able to work on the
frameworks he had to work on later.

Sworup received his Bachelor of Information Technology degree from Purbanchal


University in Nepal. He currently works with Zimris Technologies Nepal Pvt. Ltd., a
subsidiary of Zimris, LLC, as a senior developer.

Sworup likes to keep on top of the current technologies, keeping an eye on StackOverflow,
Laracasts forums, and occasional podcasts. He posts on these mediums whenever he can
and is looking to start a technical blog documenting his experiences at http://sworup.com.
np/. You can reach him at sworup.shakya@gmail.com.

I would like to thank Suzanne Coutinho, Francina Pinto and Chaitanya Nair of Packt Publishing for
giving me this opportunity and helping me through the review process. I would like to thank my
friends, family and colleagues for their unconditional support.
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at service@packtpub.com for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters and receive exclusive discounts and offers on Packt books and
eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt
books and video courses, as well as industry-leading tools to help you plan your personal
development and advance your career.

Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Table of Contents
Chapter 1: Why "Good PHP Developer" Isnt an Oxymoron 8
Coding style – the PSR standards 11
Revising object-oriented programming 11
Polymorphism 11
Traits (multiple inheritance) 16
Scalar type hints 19
Limiting debug access to private/protected properties 21
Setting up the environment with Composer 23
The Gang of Four (GoF) 26
Creational design patterns 27
Dependency injection 27
Structural design patterns 28
Behavioral design patterns 28
Architectural patterns 28
Summary 29
Chapter 2: Anti-Patterns 30
Why anti-patterns matter 31
Not invented here syndrome 34
Third-party dependencies with Composer 36
God objects 40
Environment variables in PHP source 43
Singletons (and why you should be using dependency injection) 44
Dependency injection 45
Database as IPC 45
Auto-increment database IDs 46
Cronjob imitating service 47
Software in place of architecture 47
Interface Bloat 49
Cart before the horse 51
Separation of development and operations 52
Excessive separation of development responsibilities 52
Error suppression operator 53
Blind faith 54
Sequential coupling 55
The big rewrite 58
Automated tests 59
Service splitting 60
Perfectly staged migrations 61
Tester-Driven Development 62
Bloated optimization 62
Analysis paralysis 63
Bikeshedding 63
Premature optimization 63
Uneducated manager syndrome 64
Wrong rocky foundations 64
Long methods 65
Magic numbers 70
Summary 70
Chapter 3: Creational Design Patterns 72
Software design process 72
Simple Factory 74
Factory Method 78
Abstract Factory pattern 82
Lazy initialization 90
Builder pattern 93
Prototype pattern 97
Summary 102
Chapter 4: Structural Design Patterns 103
Agile software architecture 104
Decorator 105
Adapter 108
Class Adapter 108
Object Adapter 110
FlyWeight 113
Composite 117
Bridge 120
Proxy pattern 123
Facade 127
Summary 130
Chapter 5: Behavioral Design Patterns 132
Personality traits for passionate programmers 133
Observer pattern (SplObserver/SplSubject) 135

[ ii ]
Iterators 139
IteratorAggregate 139
Iterator 141
The many iterators of PHP 142
Generators 143
Template Method design pattern 148
Chain of Responsibility 152
Strategy design pattern 159
Specification design pattern 163
Scheduled Task pattern 167
Summary 168
Chapter 6: Architectural Patterns 170
Model-View-Controller (MVC) 170
Service-oriented architecture 172
Microservices 173
Asynchronous queueing 177
Message Queue pattern (Getting started with RabbitMQ) 177
Publish-Subscriber pattern 187
Summary 191
Chapter 7: Refactoring 192
What is refactoring? 192
Test, test, and test again 193
Code smells 194
Long methods and duplicated code 195
Large class 197
Replacing complex logical statements and switch statements with
polymorphism or the Strategy Pattern 198
Duplicating code following a single control structure 200
Long Parameter List and primitive obsession 200
Indecent exposure 203
Feature envy 204
Inappropriate intimacy 206
Deeply nested statements 206
Remove assignments to parameters 207
Comments 208
Encapsulating Composite with Builder 208
Replacing hard-coded notifications with Observer 209
Replacing one/many distinctions with Composite 209

[ iii ]
Separate versions with Adapters 210
What do I tell my manager? 210
Summary 211
Chapter 8: How to Write Better Code 212
Nature of a HTTP request 212
RESTful API design 231
Stateless nature 231
Versioning 231
Filtering 232
Sorting 232
Searching 232
Limiting fields 233
Returning new fields 233
When in doubt – KISS 233
Software development life cycle 234
On Scrum, and real Agility 235
You need to sack people sometimes 237
Lean project management 239
YAGNI and defering decisions 239
Monitoring 240
Tests fight legacy 241
Behavior-Driven Development 243
Summary 250
Index 252

[ iv ]
Preface
Have you ever been to a PHP conference? If not, I’d highly recommend it, it is the closest
you can get to a living and breathing PHP community. A few weeks ago, I flew from
London to St. Louis, Misouri, to speak at php[tek] (the PHP conference run by
php[architect]). After the conference, there was a small tradition within the PHP community
known as WurstCon. Essentially, hundreds of PHP conference attendees cram themselves
into a small hot dog shop and host a hot dog convention, often to the complete surprise of
the staff there. Likewise, community nights at PHP events are the warmest and most
accepting community occasions you’ll ever run into; the PHP community is surely one that
other development language communities envy.

As of PHP 7, the PHP project has changed dramatically; but what I love, remains strong.
The warmth you will feel at any PHP conference, the openness in the documentation, and
adoption in the language. Yes, there are practices that are undoubtedly bad within PHP
itself; however, think of what the PHP community has recently achieved, ranging from
PHPUnit to Composer. Throughout this book, bear in mind the improvements in PHP 7, a
few of which I’ll share with you. The trajectory of the project is now certainly upwards, and
let’s not forget that this wasn’t always true. The PHP community has learned its lessons
from the past, whilst the language maintains the flexibility to write what is bad.

This book will seek to impart strong software engineering skills to you with the focus on
implementing them in PHP. At the time of publishing this book, there is a certain void and
a necessity for this kind of material. This book seeks to be the lighthouse that will not only
demonstrate software design theory, but also seek to impart practical information of real
value to improve the quality and maintainability of the code you write. This book leaves no
stone unturned throughout the software development cycle and will seek to confront the
reasons as to why the majority of software projects fail whilst also addressing design,
redesign, and safeguard effective code.

This book goes beyond traditional design patterns as envisaged by the Gang of Four and
details the practices that passionate PHP developers need to be successful as software
engineers or leads on detailed PHP projects. This book will introduce you to the core
knowledge required to understand project management techniques, why the majority
software development projects fail, and why you can make yours a success.
Preface

Originally, I gave thought to writing a book on PHP when Mandi Rose, who I worked with
previously, suggested I put together a book on the practices I’ve learned with PHP.
Needless to say, at the time that suggestion was made, the best of my career was
undoubtedly ahead of me; when the opportunity actually arose to write something like this,
I felt I had learned dramatically more as time progressed. By no means should you see this
book as the be-all and end-all of PHP practices; instead, you should use it to increase your
knowledge base on PHP, but by no means limit it to this. In this book, I aim to give
something, however small, back to the PHP community; after reading this book, I would
encourage you to get stuck in and share what you’ve learned with others.

Later in this book, I will advocate Extreme Programming as a methodology and courage as
a key value of this methodology. I will ask you to bear in mind the explanation of courage
in The Values of Extreme Programming: “We will tell the truth about progress and
estimates. We don't document excuses for failure because we plan to succeed. We don't fear
anything because no one ever works alone. We will adapt to changes whenever they
happen.” This is, of course, some key advice we should all follow and seek to genuinely
understand risks instead of cowering behind them. For many of us, the code we write
during parts of our career is the highest expression of our labor. Indeed, the late nights
turning into early mornings we spend debugging and developing are what ultimately allow
us to demonstrate the fruits of our labor. In essence, as software engineers, the code we
write defines who we are, as such we should be open to constantly refining and refactoring
our processes, which is what this book aims to support you in doing. I am incredibly
honored that you chose to allow me to help you to reach this end.

What this book covers


Chapter 1, Why "Good PHP Developer" Isn't an Oxymoron, introduces the concept of design
patterns as recurring solutions to commonly arising problems.

Chapter 2, Anti-Patterns, introduces how patterns can lead to decidedly negative


consequences.

Chapter 3, Creational Design Patterns, discusses Gang of Four design patterns, namely those
surrounding object creation.

Chapter 4, Structural Design Patterns, covers how multiple classes and objects can be
combined to deliver a clearer interface.

[2]
Preface

Chapter 5, Behavioral Design Patterns, explains how to increase the flexibility of


communication between objects by identifying patterns that can help with communication
between them.

Chapter 6, Architectural Patterns, revolves around resolving common issues related to the
architecture of a web application/system, potentially outside the code base itself.

Chapter 7, Refactoring, shows how to redesign code that has already been written to
improve maintainability.

Chapter 8, How to Write Better Code, covers a range of concepts that haven’t been discussed
elsewhere, and it also concludes with some advice for developers.

What you need for this book


An installation of PHP 7 will serve you well throughout this book. You should be prepared
to alter your development environment as needed throughout this book; we will address
the installation of various tools as we encounter them.

This book is not for the despairingly hostile or those who are passively antagonistic to
approaching new software engineering principles. It is not for those who seek to be lone
warriors, either. When altering a given code base, you must seek to improve the code of the
entire code base and everyone who works on it. You must be willing to take personal
responsibility of the code you write and not blame external factors. Code maintainability
cannot be improved unilaterally on shared code bases; you must write your code with the
intention of maintaining code quality for those who maintain it after you. Additionally, seek
to go into this book with the mindset of being able to share what you’ve learned, whether it
is with those in your teams, your user groups, or the larger PHP community. In other
words, approach this book with the end in mind; approach this book with the stated aim of
improving your code and those in the code base you maintain.

Who this book is for


This book is certainly aimed at the PHP developer looking to learn about the complete set of
skills needed to be a software engineer, in particular, some lessons from software design;
this book will seek to educate you on how your code can be made more extensible and
easier to develop on. This book seeks to take your code beyond just being a bag of functions
and classes, instead preferring well-designed, well-written, and well-tested code.

[3]
Preface

You will need a working knowledge of PHP and enough to build an application, but by no
means do you have to be a total expert at everything in PHP; a working knowledge of the
basics of software engineering will certainly give you a heads up.

You must encounter this book with an open mind and a willingness to have your
preconceptions about software development challenged. This book will confront some
truths about how you may be failing personally as a developer; it is vital that you approach
this book with a willingness to take these principles onboard.

This book presents a set of software development patterns and principles that you can
adopt. It is vital that you understand where these patterns should and shouldn’t be applied;
this will be explained throughout the book, especially in the last chapter.

A key tenet of reading this book is understanding what PHP is for and what it isn’t. I expect
you to enter this book understanding what problems you expect PHP to solve and what
you expect to use other software development languages to solve.

Conventions
In this book, you will find a number of text styles that distinguish between different kinds
of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The
index.php file now yields this result".

A block of code is set as follows:


<?php

abstract class Notifier


{
protected $to;

public function __construct(string $to)


{
$this->to = $to;
}

abstract public function validateTo(): bool;

abstract public function sendNotification(): string;

[4]
Preface

Any command-line input or output is written as follows:


echo $richard->hasPaws;

New terms and important words are shown in bold. Words that you see on the screen, for
example, in menus or dialog boxes, appear in the text like this: "direct your web browser to
your chosen web server and you should see Hello world! pop up on screen."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this
book—what you liked or disliked. Reader feedback is important for us as it helps us
develop titles that you will really get the most out of.

To send us general feedback, simply e-mail feedback@packtpub.com, and mention the


book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or
contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase.

Downloading the example code


You can download the example code files for this book from your account at http://www.p
acktpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.c
om/support and register to have the files e-mailed directly to you.

[5]
Preface

You can download the code files by following these steps:

1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box.
5. Select the book for which you're looking to download the code files.
6. Choose from the drop-down menu where you purchased this book from.
7. Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's
webpage at the Packt Publishing website. This page can be accessed by entering the book's
name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:

WinRAR / 7-Zip for Windows


Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPubl
ishing/Mastering-PHP-Design-Patterns/. We also have other code bundles from our
rich catalog of books and videos available at https://github.com/PacktPublishing/.
Check them out!

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books—maybe a mistake in the text or the
code—we would be grateful if you could report this to us. By doing so, you can save other
readers from frustration and help us improve subsequent versions of this book. If you find
any errata, please report them by visiting http://www.packtpub.com/submit-errata,
selecting your book, clicking on the Errata Submission Form link, and entering the details
of your errata. Once your errata are verified, your submission will be accepted and the
errata will be uploaded to our website or added to any list of existing errata under the
Errata section of that title.

[6]
Preface

To view the previously submitted errata, go to https://www.packtpub.com/books/conten


t/support and enter the name of the book in the search field. The required information will
appear under the Errata section.

Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At
Packt, we take the protection of our copyright and licenses very seriously. If you come
across any illegal copies of our works in any form on the Internet, please provide us with
the location address or website name immediately so that we can pursue a remedy.

Please contact us at copyright@packtpub.com with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable
content.

Questions
If you have a problem with any aspect of this book, you can contact us
at questions@packtpub.com, and we will do our best to address the problem.

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

As Martin Fowler put it:

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

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

Software engineers mustn't just code software; they must know how to design it. Indeed
often a good software engineer, when interviewing other software engineers will ask
questions about the design of the code itself. It is trivial to get a piece of code that will
execute, and it is also benign to question a developer as to whether strtolower or
str2lower is the correct name of a function (for the record, it's strtolower). Knowing the
difference between a class and an object doesn't make you a competent developer; a better
interview question would, for example, be how one could apply subtype polymorphism to
Why "Good PHP Developer" Isnt an Oxymoron

a real software development challenge. Failure to assess software design skills dumbs down
an interview and results in there being no way to differentiate between those who are good
at it, and those who aren't. These advanced topics will be discussed throughout this book,
by learning these tactics, you will better understand what the right questions to ask are
when discussing software architecture.

Moxie Marlinspike once tweeted the following:

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

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

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

Therefore, it is increasingly important that developers understand proper software design


practices to ensure their code maintains the long term maintainability. Indeed, another key
skill lies in refactoring code, improving the design of existing code to make it easier to extend
in the long term.

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

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

[9]
Why "Good PHP Developer" Isnt an Oxymoron

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

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

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

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

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

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

Coding style – the PSR standards


Revising object-oriented programming
Setting up the environment with Composer

[ 10 ]
Why "Good PHP Developer" Isnt an Oxymoron

Who are the Gang of Four?

Coding style – the PSR standards


When it comes to coding style, I would like to introduce you to the PSR standards created
by the PHP Framework Interop Group. Namely, the two standards that apply to coding
standards are PSR-1 (Basic Coding Style) and PSR-2 (Coding Style Guide). In addition to
this, there are PSR standards that cover additional areas, for example, as of today; the PSR-4
standard is the most up-to-date autoloading standard published by the group. You can find
out more about the standards at http://www.php-fig.org/.

Coding style being used to enforce consistency throughout a code base is something I
strongly believe in. It does make a difference to your code readability throughout a project.
It is especially important when you are starting a project (chances are you may be reading
this book to find out how to do that right) as your coding style determines the style the
developers following you in working on this project will adopt. Using a global standard
such as PSR-1 or PSR-2 means that developers can easily switch between projects without
having to reconfigure their code style in their IDE. Good code style can make formatting
errors easier to spot. Needless to say that coding styles will develop as time progresses, to
date I elect to work with the PSR standards.

I am a strong believer in the phrase: always code as if the guy who ends up maintaining your code
will be a violent psychopath who knows where you live. It isn't known who wrote this phrase
originally, but it's widely thought that it could have been John Woods or potentially Martin
Golding.

I would strongly recommend familiarizing yourself with these standards before proceeding
in this book.

Revising object-oriented programming


Object-oriented programming is more than just classes and objects; it's a whole
programming paradigm based around objects (data structures) that contain data fields and
methods. It is essential to understand this; using classes to organize a bunch of unrelated
methods together is not object orientation.

Assuming you're aware of classes (and how to instantiate them), allow me to remind you of
a few different bits and pieces.

[ 11 ]
Why "Good PHP Developer" Isnt an Oxymoron

Polymorphism
Polymorphism is a fairly long word for a fairly simple concept. Essentially, polymorphism
means the same interface is used with a different underlying code. So multiple classes could
have a draw function, each accepting the same arguments, but at an underlying level, the
code is implemented differently.

In this section, I would like to talk about Subtype Polymorphism in particular (also known
as Subtyping or Inclusion Polymorphism).

Let's say we have animals as our supertype; our subtypes may well be cats, dogs, and
sheep.

In PHP, interfaces allow you to define a set of functionality that a class that implements it
must contain, as of PHP 7 you can also use scalar type hints to define the return types we
expect.

So for example, suppose we defined the following interface:


interface Animal
{
public function eat(string $food) : bool;

public function talk(bool $shout) : string;


}

We could then implement this interface in our own class, as follows:


class Cat implements Animal {
}

If we were to run this code without defining the classes we would get an error message as
follows:
Class Cat contains 2 abstract methods and must therefore be declared
abstract or implement the remaining methods (Animal::eat, Animal::talk)

Essentially, we are required to implement the methods we defined in our interface, so now
let's go ahead and create a class that implements these methods:
class Cat implements Animal
{
public function eat(string $food): bool
{
if ($food === "tuna") {
return true;
} else {

[ 12 ]
Why "Good PHP Developer" Isnt an Oxymoron

return false;
}
}

public function talk(bool $shout): string


{
if ($shout === true) {
return "MEOW!";
} else {
return "Meow.";
}
}
}

Now that we've implemented these methods, we can then just instantiate the class we are
after and use the functions contained in it:
$felix = new Cat();
echo $felix->talk(false);

So where does polymorphism come into this? Suppose we had another class for a dog:
class Dog implements Animal
{
public function eat(string $food): bool
{
if (($food === "dog food") || ($food === "meat")) {
return true;
} else {
return false;
}
}

public function talk(bool $shout): string


{
if ($shout === true) {
return "WOOF!";
} else {
return "Woof woof.";
}
}
}

Now let's suppose we have multiple different types of animals in a pets array:
$pets = array(
'felix' => new Cat(),
'oscar' => new Dog(),

[ 13 ]
Why "Good PHP Developer" Isnt an Oxymoron

'snowflake' => new Cat()


);

We can now actually go ahead and loop through all these pets individually in order to run
the talk function. We don't care about the type of pet because the talk method that is
implemented in every class we get is by virtue of us having extended the Animals interface.

So let's suppose we wanted to have all our animals run the talk method. We could just use
the following code:
foreach ($pets as $pet) {
echo $pet->talk(false);
}

No need for unnecessary switch/case blocks in order to wrap around our classes, we just
use software design to make things easier for us in the long-term.

Abstract classes work in a similar way, except for the fact that abstract classes can contain
functionality where interfaces cannot.

It is important to note that any class that defines one or more abstract classes must also be
defined as abstract. You cannot have a normal class defining abstract methods, but you can
have normal methods in abstract classes. Let's start off by refactoring our interface to be an
abstract class:
abstract class Animal
{
abstract public function eat(string $food) : bool;

abstract public function talk(bool $shout) : string;

public function walk(int $speed): bool {


if ($speed > 0) {
return true;
} else {
return false;
}
}
}

You might have noticed that I have also added a walk method as an ordinary, non-abstract
method; this is a standard method that can be used or extended by any classes that inherit
the parent abstract class. They already have their implementation.

Note that it is impossible to instantiate an abstract class (much like it's not possible to
instantiate an interface). Instead, we must extend it.

[ 14 ]
Why "Good PHP Developer" Isnt an Oxymoron

So, in our Cat class let's remove the following:


class Cat implements Animal

We will replace it with the following code:


class Cat extends Animal

That's all we need to refactor in order to get classes to extend the Animal abstract class. We
must implement the abstract functions in the classes as we outlined for the interfaces, plus
we can use the ordinary functions without needing to implement them:
$whiskers = new Cat();
$whiskers->walk(1);

As of PHP 5.4 it has also become possible to instantiate a class and access a property of it in
one system. PHP.net advertised it as: Class member access on instantiation has been added, e.g.
(new Foo)->bar(). You can also do it with individual properties, for example, (new
Cat)->legs. In our example, we can use it as follows:

(new \IcyApril\ChapterOne\Cat())->walk(1);

Just to recap a few other points about how PHP implemented OOP, the final keyword
before a class declaration or indeed a function declaration means that you cannot override
such classes or functions after they've been defined.

So, let's try extending a class we have named as final:


final class Animal
{
public function walk()
{
return "walking...";
}
}

class Cat extends Animal


{
}

This results in the following output:


Fatal error: Class Cat may not inherit from final class (Animal)

Similarly, let's do the same except at a function level:


class Animal
{

[ 15 ]
Why "Good PHP Developer" Isnt an Oxymoron

final public function walk()


{
return "walking...";
}
}

class Cat extends Animal


{
public function walk () {
return "walking with tail wagging...";
}
}

This results in the following output:


Fatal error: Cannot override final method Animal::walk()

Traits (multiple inheritance)


Traits were introduced in PHP as a mechanism for introducing Horizontal Reuse. PHP
conventionally acts as a single inheritance language, because of the fact that you can't
inherit more than one class into a script.

Traditional multiple inheritance is a controversial process that is often looked down upon
by software engineers.

Let me give you an example of using Traits first hand; let's define an abstract Animal class
that we want to extend into another class:
class Animal
{
public function walk()
{
return "walking...";
}
}

class Cat extends Animal


{
public function walk () {
return "walking with tail wagging...";
}
}

[ 16 ]
Why "Good PHP Developer" Isnt an Oxymoron

So now let's suppose we have a function to name our class, but we don't want it to apply to
all our classes that extend the Animal class, we want it to apply to certain classes
irrespective of whether they inherit the properties of the abstract Animal class or not.

So we've defined our functions like so:


function setFirstName(string $name): bool
{
$this->firstName = $name;
return true;
}

function setLastName(string $name): bool


{
$this->lastName = $name;
return true;
}

The problem now is that there is no place we can put them without using Horizontal Reuse,
apart from copying and pasting different bits of code or resorting to using conditional
inheritance. This is where Traits come to the rescue; let's start off by wrapping these
methods in a Trait called Name:
trait Name
{
function setFirstName(string $name): bool
{
$this->firstName = $name;
return true;
}

function setLastName(string $name): bool


{
$this->lastName = $name;
return true;
}
}

So now that we've defined our Trait, we can just tell PHP to use it in our Cat class:
class Cat extends Animal
{
use Name;

public function walk()


{
return "walking with tail wagging...";

[ 17 ]
Why "Good PHP Developer" Isnt an Oxymoron

}
}

Notice the use of the Name statement? That's where the magic happens. Now you can call
the functions in that Trait without any problems:
$whiskers = new Cat();
$whiskers->setFirstName('Paul');
echo $whiskers->firstName;

All put together, the new code block looks as follows:


trait Name
{
function setFirstName(string $name): bool
{
$this->firstName = $name;
return true;
}

function setLastName(string $name): bool


{
$this->lastName = $name;
return true;
}
}

class Animal
{
public function walk()
{
return "walking...";
}
}

class Cat extends Animal


{
use Name;

public function walk()


{
return "walking with tail wagging...";
}
}

$whiskers = new Cat();


$whiskers->setFirstName('Paul');
echo $whiskers->firstName;

[ 18 ]
Exploring the Variety of Random
Documents with Different Content
Passages such as these are often employed as a rhetorical flourish
at the end of a chapter. They are analogous to what actors call ‘making
a good exit.’ In Bancroft they constitute for pages together the
prevailing rather than the exceptional form. The reader, whether
conscious of it or not, is kept on a strain. At last he grows
uncomfortable. He wishes the historian would cease to declaim, would
come down from the rostrum, throw aside his academic robes, and be
neighborly and familiar.
This History was so long in the writing that Bancroft’s style changed
materially. The opinion prevails that his diction improved as the work
proceeded, that the later volumes are uniformly less inflated, strained,
and ‘eloquent’ than the earlier ones. It is true that he made innumerable
revisions of the text. The changes were not always improvements.
Sometimes in rewriting a sentence he made it less energetic. Strong
expressions were softened. A plain old-fashioned word would be taken
out; often it carried the whole phrase with it. Whether the literary or the
historical sense dictated the change in question cannot always be
determined.
Bancroft’s diction is manly and forceful, but it lacks natural grace
and suppleness; it is flexible as chain armor is flexible, but not as is the
human body. It may be doubted whether he is ever read for literary
pleasure. Nevertheless, scattered through these twelve volumes are
hundreds of passages well worth the study of those who enjoy an
exhibition of mastery in the use of words.

IV
THE HISTORY OF THE UNITED STATES
One does well to read Bancroft in the tall, wide-margined, and almost
sumptuous volumes of the original editions. The page is open and
inviting. Both text and notes have a personal flavor very diverting at
times. There is no question as to the usefulness of an attractive page in
works of this sort. Political histories should be made easy, not by
picture-book methods, but by the legitimate arts of good printing.
The work is generously planned. Twelve octavo volumes are
required to bring the narrative down to the ratification of the
16
constitution. Three volumes, comprising nearly fifteen hundred pages,
are given to the Colonial period alone.
Bancroft announced his theory of historical writing in the preface of
1834. He was to be controlled always by ‘the principles of historical
scepticism,’ and his narrative was to be drawn ‘from writings and
sources which were contemporaries of the events that are described.’
Nothing commonly supposed to belong to American history was to be
retained merely because it had been unchallenged by former
historians.
The treatment, as shown in these volumes on the Colonial period,
is in perfect accord with the author’s conception of the dignity of the
subject. The matter is as stately as the manner. Bancroft writes history
as a lord high chamberlain conducts a court function. He feels that
during the ceremony of discovering a world and planting a nation there
should be no unseemliness, certainly no laughter or disturbance.
The characters go through their evolutions like well-drilled courtiers.
So stately are they as to appear scarce human. Homely and familiar
traits are almost completely suppressed. The founders of America, as
we see them looming in the pages of Bancroft, are not men but
incarnate ideas. They are the embodiment of principles and virtues.
Winthrop is enlightened conservatism, Vane is generous impetuosity,
Roger Williams is liberty of conscience. Strive how we will to bring
these men nearer, to make them tangible, the effort is not wholly
successful. These figures of the past, like the characters of a morality-
play, persist in remaining personified ideas.
As a reaction against ‘classical’ history comes history of the
gossiping school. ‘Thanks to you,’ said Brunetière, welcoming Masson
to the French Academy, ‘we now know the exact number of Napoleon’s
shirts.’ Bancroft was not interested in the spindles and shoe-buckles of
the Puritans. Many people are, but they must find elsewhere the
gratification they seek. Whoever wishes at any time absolutely to
escape anecdotage, homely detail, and piquant gossip, has it always in
his power to do so; he can read Bancroft’s three volumes on the
Colonial period and dwell among abstractions.
Even if not at this stage of his career the most human of writers,
Bancroft is a comforting historian to return to, after having dwelt for a
while with those who instruct us how low and mercenary in motive, how
impervious to liberal ideas, were the men who planted English
civilization in America. Historical iconoclasts all, they are frightfully
convincing. Some of their arguments lose a degree of force as it dawns
on the reader that Seventeenth-century men are being judged by
Nineteenth-century standards. When Bancroft wrote, the habit of
abusing the ancestors had not become deep-seated.
Turning from the Colonial period, the historian takes up the period
of the American Revolution. Seven volumes are required for telling the
story. The logical arrangement is by ‘epochs.’ They are four in number:
‘Overthrow of the European Colonial system,’ ‘How Great Britain
estranged America,’ ‘America declares itself independent,’ ‘The
17
Independence of America is acknowledged.’
General histories must treat of many things, the doings of
authorized and representative assemblies and the doings of the mob,
skirmishes, battles by land and sea, diplomatic intrigues, party
combinations, political and military plots, the characters of the actors in
the historic drama, and the setting of the stage on which they played.
While doing all parts of his task with workmanlike skill, a historian will
be found to excel in this thing or in that. Bancroft’s accounts of military
operations are always clear, energetic, and often extremely readable.
He could not, like Irving, ‘render you a fearful battle in music,’ but he
never made the mistake of supposing that he could. He had not the
graphical power of Parkman, but he had enough for his purposes.
His character sketches of the men who figured in the struggles for
American independence are among the best parts of his writing. The
patriots and their friends in England and on the Continent are too
uniformly creatures of light, but their opponents are not represented as
necessarily creatures of darkness. If Bancroft could be more than fair to
his own side, he was incapable of being wholly unfair to the other. His
tendency is to regard human character as all of a piece, fixed rather
than fluctuating. Men (politicians included) have been known to grow in
virtue as they grow in years. Bancroft was over complacent in his
attitude towards frenzied impromptu Revolutionary gatherings whose
motives could not always have been so guiltlessly patriotic and
18
disinterested as he represents them. He was but little versed in the
psychology of mobs.
Forceful at all points, Bancroft was singularly impressive in dealing
with history as it is made in parliaments and conventions, in council
chambers, cabinets, and courts of law. He was born to grapple with
whole state paper offices. He knew the secret of subordinating a vast
amount of detail to his main purpose. An important part of the American
Revolution took place in Europe. Bancroft’s capital merit consists in his
having brought the event into its largest relations. The story as he told it
did not merely concern the uprising of a few petty quarrelsome
colonies, it became an important chapter in the history of liberty. Not for
an instant did he permit himself to lose sight of that ‘idea of continuity
which gives vitality to history.’
It is wonderful how through these seven volumes everything bends
to one idea; how it all becomes part of a demonstration, a detail in the
history of that spirit which, acting through discontent, led first to local
outbreak and resistance, then to concerted action and war, and finally
to the birth of a new nation.
The crown of Bancroft’s work is the story of how the states parted
with so much of their individuality as stood in the way of union, and
then united. Two volumes would seem to afford room for full and
leisurely treatment. But in fact the historian only accomplished his task
by enormous compression. Often the substance of a speech had to be
given in a sentence, and the deliberations of days in a few paragraphs.
The marshalling of facts, the grasp of the subject in detail and as a
whole, are extraordinary. Bancroft notes what forces led to union and
what opposed it. He marks the shifting of public sentiment, the
trembling of the balance, but he grants himself few privileges of the sort
called literary. Seldom dramatic or picturesque in this portion of his
narrative, he is at all times logically exact and magisterial.

* * * * *
There is a peculiar fitness in the word ‘monumental’ applied to
Bancroft’s work. It has solidity, strength, durability, a massive and
stately grandeur. It is a book which the modern reader finds it easy to
neglect; but he puts it in his library and never fails to commend it to his
friends, with a hypocritical expression of surprise at their not being
better acquainted with it. The truth is, we are spoiled by more attractive
historians. Macaulay, Froude, and Parkman have made us indolent,
fond of verbal comforts and disinclined to effort. We demand not only to
be instructed but to be vastly entertained at the same time. Bancroft
certainly instructs; it would be difficult to prove that he also entertains.
His tone of confident eulogy is often condemned. On the whole, this
is a merit rather than a fault. Doubtless he admired too uniformly and
too much. Many writers have taken pleasure in showing that his
admiration was misplaced. And thus a balance is kept. It is a fortunate
thing for American literature that Bancroft’s vast work, destined to so
wide an influence, and the fruit of such immense labor, should have
been conceived and written in a generous and hopeful spirit. The
English reviewer who on the appearance of the first volume praised the
historian because he was ‘so fearlessly honest and impartial’ might also
have praised him because he was so fearlessly optimistic. This too
requires courage.

FOOTNOTES:
11
Bancroft was twice married. His second wife was Mrs. Elisabeth
(Davis) Bliss.
12
For an account of the privileges he enjoyed in making his
collections see Winsor’s Narrative and Critical History of America,
vol. viii, p. 477.
13
W. M. Sloane.
14
T. W. Higginson in ‘The Nation,’ January, 1891.
15
Bancroft’s characteristics as a young man are admirably brought
out in the recently printed selection from his letters and journals,
edited by M. A. DeWolfe Howe. ‘Scribner’s Magazine,’
September and October, 1905.
16
Two volumes of the original edition correspond to one volume of
the ‘author’s last revision,’ 1883–85.
17
In the ‘last revision’ Epoch Four is divided into unequal parts and
the titles are reworded: Epoch first, ‘Britain overthrows the
European colonial system,’ 1748–63; Epoch second, ‘Britain
estranges America,’ 1763–74; Epoch third, ‘America takes up
arms for self-defence and arrives at independence,’ 1774–76;
Epoch fourth, ‘America in alliance with France,’ 1776—80; Epoch
fifth, ‘The People of America take their equal station among the
powers of the earth,’ 1780 to December, 1782.
18
J. F. Jameson speaks of Bancroft’s ‘tendency to conventionalize,
to compose his American populations of highly virtuous Noah’s-
ark men.’ History of Historical Writing in America, 1891, p. 108.
V
William Hickling Prescott

REFERENCES:

George Ticknor: Life of William Hickling Prescott,


1864.
Rollo Ogden: William Hickling Prescott, ‘American
Men of Letters,’ 1904.
H. T. Peck: William Hickling Prescott, ‘English Men
of Letters,’ 1905.

I
HIS LIFE

The Prescotts are an ancient family as antiquity is reckoned in the


United States. The first Anglo-American of that name, John Prescott,
an old Cromwellian soldier, took up residence in this country about
1640, and after living awhile at Watertown, Massachusetts, made a
permanent home for himself at Lancaster, then a frontier settlement.
When thieving Indians plundered him, it is said that he used to put
on helmet, gorget, and cuirass, and start in pursuit. Being a powerful
man and stern of countenance, his terrific appearance in his armor
had a salutary effect on the red men.
Jonas Prescott, a son of the old warrior, settled at Groton,
Massachusetts, and there the family history centres for more than a
hundred years. They were a vigorous race, useful and conspicuous
in the military and civil affairs of the colony.
William Hickling Prescott, the historian, was born in Salem,
Massachusetts, on May 4, 1796. His father, Judge William Prescott,
was a man of eminent abilities, esteemed for his great legal
acquirements and beloved for his personal worth. His mother,
Catharine Hickling, a daughter of Thomas Hickling of Boston, was
distinguished for energy and benevolence, as well as for a certain
gayety of temperament, a trait which she transmitted to her famous
son. The grandfather of the historian was Colonel William Prescott,
founder of the town of Pepperell, who, on the night of June 16, 1775,
with his force of a thousand men, threw up a redoubt on Bunker
(Breed’s) Hill, and on the following day defended it until defence was
no longer possible.
Prescott was drilled in the classics by one of old Parr’s pupils,
the Reverend Doctor John Gardiner, rector of Trinity Church, Boston.
He was an insatiable reader of books; but it were idle to assume that
his interest in Spanish history and literature took its first impulse, as
has been asserted, from the reading of Southey’s translation of
Amadis of Gaul.
He entered Harvard College in the Sophomore year and was
graduated in 1814. A misfortune befell him early in his course which
changed his whole life and made enormous demands on his
philosophy and courage. In one of the frolics attending the breaking
up of commons, when small missiles were flying about the room,
Prescott was struck full in the left eye with a hard crust of bread. The
sight was instantly destroyed, and he lived for years in apprehension
of what, fortunately, never overtook him, total blindness.
He began the study of law, but illness and consequent
weakening of the power of vision put an end to it. In search of health
and diversion he went abroad. After spending some months in the
Azores, in the family of his maternal grandfather, Thomas Hickling,
then United States consul at St. Michael’s, he visited Italy, France,
and England. In London he consulted eminent oculists, who were
able, however, to give him but little encouragement.
Shortly after his return home he married Miss Susan Amory of
Boston, whose maternal grandfather, Captain Linzee, was in
command of a British sloop of war at the outbreak of the Revolution,
and had cannonaded the redoubt on Bunker Hill. In 1821 Prescott
planned a course of literary study. Beginning oddly enough with
grammars and rhetorics, he followed this preliminary reading with a
wide survey first of English literature, then of French and Italian.
German he tried and gave up. With his enfeebled sight he could do
but little of the actual reading for himself; the bulk of it had to be
done for him.
Prescott’s literary life was peculiar in that he prepared himself to
become a man of letters with no definite conception of what he
would write about. He was not, like the literary heroes of whom we
read, so possessed of his subject from boyhood that all the ancient
neighbors distinctly recall early evidences of his predilection. His first
impulse towards the studies in which he won renown came from
George Ticknor. To help Prescott pass away his time Ticknor read to
his friend the lectures he had been giving to advanced classes at
Harvard, lectures which formed the basis of his History of Spanish
Literature. This was in 1824. Prescott became enthusiastic over the
study of the Spanish language and history. A year later he was
thinking what brilliant passages might be written on the Inquisition,
the Conquest of Granada, and the exploits of the Great Captain.
After balancing Italian and Spanish subjects against each other, he
decided, not without misgivings, on a history of Ferdinand and
Isabella, and early in 1826 wrote to Alexander H. Everett, United
States minister at Madrid, asking his help in collecting materials.
Three and a half years of study preceded the writing of the first
chapter; ten and a half years in all were required to make the book.
Its enthusiastic reception from scholars and public alike led Prescott
to take up cognate subjects. The list of his writings is brief, but,
taking into account the difficulties involved, one may say without
exaggeration that Prescott’s historical works represent a labor little
short of titanic.
The History of the Reign of Ferdinand and Isabella the Catholic
appeared in 1837. It was followed by The Conquest of Mexico, 1843;
Critical and Historical Essays, 1845 (consisting chiefly of papers
reprinted from the ‘North American Review’); The Conquest of Peru,
1847; The History of Philip the Second, 1855 (left unfinished at the
author’s death). To this list of important works may be added a brief
continuation of Robertson’s Charles the Fifth, and a Memoir of
Abbott Lawrence.
Prescott’s life was without marked external incident. His
surroundings were ideal. Having inherited a fortune, he could give
himself to toilsome literary undertakings with no care for the financial
result. He took satisfaction in the thought of having refuted
Johnson’s dictum that no man could write history unless he had
good eyes.
Early in 1858 Prescott was stricken with apoplexy, but so far
recovered as to be able to resume work on the History of Philip the
Second. A second attack (January 27, 1859) ended in his death.

II
PRESCOTT’S CHARACTER
To those who knew him in varying degrees of intimacy, whether as
friends, neighbors, or chance acquaintance, Prescott seemed the
incarnation of urbanity, thoughtfulness, good humor. To us who know
him only through the story of his life he seems notable for his heroic
qualities.
He had enormous courage and force of will. That other men
have performed great tasks under like difficulties cannot lessen the
glory of his individual achievement. Handicapped by partial
blindness, he wrote history, a type of literature which makes the most
exacting demands on the physical powers.
Had Prescott’s genius inclined him towards poetry or fiction, the
heroic element in his literary life would have been less noteworthy. In
general a novelist is not expected to read; what is chiefly required of
him in the way of preparation is, that he shall observe, feel, and
occasionally think—but not read; much reading makes a dull story-
teller. The novelist gleans material as he walks the street. For his
purpose an hour of talk with ‘a set of wretched un-idea’d girls,’ as
Doctor Johnson half affectionately, half pettishly, called them, is
worth ten hours over a book. History is another matter. The historian
must often read a thousand pages in order to write one. And the
work of preparation is indescribably exhausting; there is so much
detail to set in order, so many documents to be consulted, such a
wilderness of notes to be arranged, compared, and fitted into place.
The task, difficult under the best conditions, must seem endless to
any one with an imperfect sense.
A man with good eye-sight is like a man with the free use of his
legs, he goes where he pleases. But a scholar with defective vision
is an invalid in a wheeled chair. Prescott, being denied one of the
greatest conveniences of study, was forced to try expedients. With
most writers pen and ink are an indispensable aid to composition.
Prescott used memory instead. Not only was the knowledge
accumulated, arranged, and weighed, but it was put into literary
form, the paragraphs measured and the sentences polished before
the actual writing was begun. Prescott often carried in his head, for
days at a time, the equivalent of sixty pages of printed text, and on
occasion, seventy-five pages. Only by reflecting on the difficulties
met and overcome can the amateur of literature arrive at a
conception of Prescott’s indomitable courage.
Add to force and persistency of purpose another notable trait, a
passion for nobility of character. Prescott, unwearied in self-
examination, studied his own moral nature as he studied the pages
of his manuscript, that he might weed out the faults. The methods he
employed to this end were often whimsical, and even childlike; but in
their touching simplicity lies the best proof of the genuineness of the
motive that prompted them.
III
THE WRITER
Prescott gave unusual measure of time and thought to the
problem of expression. With a view to grounding himself in the
technical part of literature, he invoked the aid of those now forgotten
worthies, Lindley Murray and Hugh Blair—how greatly to his
advantage would be difficult to say. Books of this sort are so often
disfigured by a vicious or, what is worse, a commonplace style that it
is a question whether one does not lose by example all that he gains
by precept.
Escaping these influences, Prescott took up the chief English
authors, beginning with Ascham, Sidney, Bacon, Browne, Raleigh,
and Milton. His mind was constantly on the alert to discover by what
means these masters produced their effects. His journals show how
painstaking he was in these studies, with what intense interest he
turned the problem of the art of expression over and over in his
mind.
When he came to print, it was observed first of all that he had a
‘style.’ The self-conscious literary workman was plainly visible.
Prescott had evidently aimed to produce certain effects through the
balance of his periods, the choice of his words, the length and
structure of his sentences. Every one said: ‘He is an artist.’ Praise
could not have been more aptly bestowed. Among many eminent
artists in words Prescott was one of the most conscientious.
But the literary style of the Ferdinand and Isabella had the defect
of being too apparent. One often found himself taking note of the
manner of expression before he took note of the thought. The
panoply of words glittered from afar. It was brilliant but metallic,
magnificent but artificial.
The criticism of his first book taught Prescott the futility of
worrying about style—after one has worried sufficiently. He was no
less anxious to improve; he noted the mannerisms into which he had
fallen, resolved to correct them, and that was the conclusion of the
whole matter. He stopped dwelling overmuch on the fashion of his
writing, and at once gained in ease and naturalness. After ten years
of labor he had mastered the materials of his art. His workmanship
improved to the last. The volumes of the History of Philip the Second
have literary characteristics so gracious as to add sharpness to the
regret that this noble work had to be left unfinished.

IV
THE HISTORIES
The Ferdinand and Isabella is not a formidable book for size. A timid
reader, shrinking from fifteen hundred pages of any literature but
fiction, need not fear mortgaging too much of his time in the perusal.
Compared with a reading of Freeman’s Norman Conquest or
Carlyle’s Frederick, his task is light.
In an introductory section Prescott traces the growth of Castile
and Aragon, with their dependencies, up to the time when Ferdinand
and Isabella come on the stage of history. Perhaps there is a lack of
detail here and there. One would like to know the steps of the
process by which the Spaniards regained the territory from which
they had been driven by the Saracenic invasion of the Eighth
Century. Bitter as were the jealousies and quarrels of the various
petty states, they made common cause against the Mohammedans.
They hated the hereditary enemy both as infidels and usurpers.
Hatred fostered the national spirit.
The history proper is divided into two parts. The first has chiefly
to do with the internal policy of Ferdinand and Isabella. It was the
period when law displaced anarchy. The law might be severe or
even unjust, but it was at all events law. Here is shown how the
power of the nobles was curbed, warring factions pacified, banditti of
all sorts kept within bounds, and that too whether they lived in
castles or lurked in dark corners, heresy suppressed in a truly
rigorous fashion, above all the national ideal strengthened. To use a
homely figure, Ferdinand and Isabella took up the problem of
national housekeeping and handled it as it had never been handled
before. A reign of order and economy was inaugurated. Thieving
servants were put under restraint or discharged, poachers were
apprehended, and the gypsies who had impudently camped on the
best part of the estates were driven off. A government which for
years had run at loose ends was now under masterful control.
The second part illustrates the foreign policy of the two
monarchs. Having made a nation out of an assemblage of turbulent
states, Ferdinand and Isabella were enabled to take a conspicuous
place among the sovereigns of Europe. By good fortune in war and
in discovery, by diplomatic shrewdness and religious zeal, their
influence was felt throughout Europe and over the seas. Spain was
no longer isolated. Her name carried weight; her will was respected.
Much of the narrative proceeds by divisions each of which might
have been printed as a monograph. A certain amount of space is
given to the Inquisition, so much to the war in Granada, so many
chapters to the history of Columbus, so many to the colonial policy,
to the Italian wars, to the life of Gonsalvo of Cordova, to the career of
Cardinal Ximenes.
While in no sense neglecting the constitutional side of the
problems before him, the historian’s bent is to the biographical and
pictorial phases of the reign. On these he dwells with satisfaction
and often in detail. To him history is a pageant. The rich coloring of
the period first attracted Prescott; he can hardly be blamed for
painting his canvas in lively hues, for so he conceived the design.
Neutral tints and dull tones are wholly wanting. The blackness of
certain events only serves to bring out in stronger relief the
resplendent brightness of virtuous acts and the goodness of noble
characters. Torquemada offsets Isabella; the cruelty of war is
forgotten in the splendor of chivalric deeds.
It is not a history of the people of Spain. The people are not
forgotten; the struggle of the commons for recognition, for justice, for
the right to be themselves and express their individuality—these
things are taken into account. But the work belongs rather to that
older school of history which concerns itself for the most part with
wars and royal progresses, with the intrigues of councillors, the
machinations of prelates, the rivalries of great houses and powerful
orders.
The History of the Conquest of Mexico is of about the same
length as its predecessor. The narrative, simpler in some ways and
more vivacious in others, is gorgeously colored throughout. Prescott
was disturbed by the picturesqueness of his own treatment. ‘Very
like Miss Porter’ and ‘Rather boarding schoolish finery’ were his
comments on certain chapters.
The first of the seven ‘books’ into which the work is divided
contains an account of Aztec civilization. Sixty years have elapsed
since these pages were written, during which time American
archæology has made great advances. That the value of Prescott’s
introduction is not wholly destroyed is due to the healthy sceptical
spirit which controlled his work.
The story has every element of romance. A young Spanish
gentleman, handsome, witty, daring, an idler in college and a
libertine, joins the army of adventurers in the New World. For ten or
fifteen years he leads the life of men of his class. He becomes a
planter in Hayti and varies the monotony of watching Indians till the
soil by suppressing insurrections of their brother Indians.
He goes to Cuba as secretary to the governor of that island,
quarrels with his chief, makes his peace, and quarrels with him
again. Thrown repeatedly into prison, he escapes with the ease of a
Baron Trenck. Reconciled to the governor, he is appointed to lead an
expedition into the newly discovered kingdom of Mexico. On this
venture he stakes his every penny. With five hundred soldiers he
proposes to subdue the natives; two priests go along to convert the
natives as fast as they are subdued. His sailors number one hundred
and ten; his pilot had served under Columbus.
Arriving on the coast, he secretly scuttles his ships, all but one,
that there may be no retreat, and then begins that wonderful march
to the great city of the Aztecs. He fights by craft as well as by
physical force. The jealousy of mutually hostile tribes helps to win his
battles. Superstition comes to his aid, for the Spaniards are thought
to be gods, and the horses they bestride carry terror into the hearts
of the natives.
At length he makes his entry into the city of flowers, and takes
up his abode there, Cortés and his little army of four hundred and
fifty Spaniards, with twice as many native allies, among sixty
thousand cannibals. Boldness marks every step of his course. He
seizes the native ‘king,’ suppresses plots with rigor, and proves his
divinity by tearing down one of the sacrificial pyramids and planting
the cross in its stead. Leaving a lieutenant in command, he hastens
back to the seashore to transact military business there. The
lieutenant precipitates a quarrel and slaughters Indians by the
hundred. Cortés returns and finds his work must be done again. This
time it is thoroughly done. Every step of his progress is marked with
blood, and the story of la noche triste and the siege of Mexico are
among the most romantic passages in the history of the New World.
In estimating men Prescott aimed to employ the standard of their
day. When Cortés lifts up his hands, red with the blood of the
miserable natives, to return thanks to Heaven for victory, the
historian does not permit himself to forget that this savage Spaniard
was a typical soldier of the Cross. ‘Whoever has read the
correspondence of Cortés, or, still more, has attended to the
circumstances of his career, will hardly doubt that he would have
been among the first to lay down his life for the Faith.’ According to
Prescott, the charge of cruelty cannot be brought against Cortés.
‘The path of the conqueror is necessarily marked with blood. He was
not too scrupulous, indeed, in the execution of his plans. He swept
away the obstacles which lay in his track; and his fame is darkened
by the commission of more than one act which his boldest apologists
will find it hard to vindicate. But he was not wantonly cruel. He
allowed no outrage on his unresisting foes.’ The historian likens the
Spaniard to Hannibal in his endurance, his courage, and his
unpretentiousness.
Later scholarship has assailed portions of The Conquest of
Mexico with needless asperity. Prescott could hardly be expected to
avail himself prophetically of archæological facts not known until
thirty years after his time. Nor was his faith in the early Spanish
accounts of the Conquest quite as childlike and uncritical as it is
sometimes represented. Historians are the most substantial of men
of letters; but they now and then build card houses which topple
down under the breath of a single new fact. And they take a very
human delight in blowing over one another’s structures. For which
reason the reading of history is a fearful joy, like skating on thin ice.
The pleasure is intense so long as nothing gives way. Perhaps the
layman is unreasonable in his demand for knowledge that shall not
require too frequent revision. He can at least read for pleasure,
hoping that a part of what he reads is true, and holding himself
prepared to relinquish the parts he likes best when the time comes.
In the History of the Conquest of Peru the author brings fresh
proof that whatever may be said of his morals, the Spanish soldier
cannot be over-praised for his valor. Pizarro was a marvel of courage
and endurance. Fanaticism, which explains much in his character,
does not explain where such tremendous physical power came from.
And he had the true theatrical bravado of the Sixteenth-century
adventurer. Add to the native histrionic gifts of the Latin race a
special training, such as life in the New World gave, and men like
Ojeda, Balboa, Cortés, and Pizarro come into existence quite
naturally. They did wonders in the coolest possible way, and with a
fine sense of the pictorial aspect of their undertakings. Pizarro,
drawing a line from east to west on the sand with his sword and
calling on his comrades to choose each man what best becomes a
brave Castilian (‘For my part I go to the south’), is a figure for
romantic drama. An Englishman equally daring would have been
more or less awkward in a pose of this sort, but the Spaniard was
perfectly at home. Of what clay were these men compounded that
they could imagine such exploits and succeed in them too?
The performance of Pizarro was less splendid than that of
Cortés and the man himself less interesting. The conqueror of
Mexico was a gentleman; not so the hard soldier who subdued the
kingdom of the Incas. His was a violent career, steeped in blood, and
ending in assassination. Not only was Pizarro without fear, but of two
courses he seized upon the more dangerous as the better suited to
his genius. Too ignorant to sign his own name, he could control not
alone the brutal soldier but as well the lawyer and the priest. Aside
from his masterfulness there was little to admire in his character.
Brute force excites wonder, but the exhibition of it becomes
wearisome at last. To Prescott ‘the hazard assumed by Pizarro was
far greater than that of the Conqueror of Mexico.’ Otherwise the man
was a mere bungler upon whom Fortune, with characteristic levity,
chanced for a time to smile. Prescott describes him in a sentence:
‘Pizarro was eminently perfidious.’ Furthermore, the conqueror of
Peru was not original; he repeated what he had learned from Balboa
and Cortés. Had he chanced upon a country less rich and civilized, it
may well be doubted whether he would have made any considerable
figure in history. The argument from gold was entirely conclusive in
those days; just as at the present time an undertaking is said to
‘succeed’ if it pays financially. Manners have improved, but ideals of
‘success’ are pretty much what they were four hundred years ago.
When Pizarro extorted from the wretched Atahualpa a promise to fill
a room twenty-two feet by seventeen to the height of nine feet with
gold, his place in history was assured. The swineherd had become
immortal.
Strange is it that the name of Francisco Pizarro should be a
household word while that of his brother Gonzalo is but little known
and seldom repeated. Yet there are few episodes in the history of
Spanish colonization more striking than the story of Gonzalo
Pizarro’s march across the Andes and the discovery of the river
Amazon. It is a tale of horror and suffering to which only the pen of a
Defoe could do justice. Gonzalo not only survived the fearful journey,
but had strength enough left to head a party for revolt against the
viceroy, Blasco Nuñez, and the execution of the Ordinances. Like a
true Pizarro, this conqueror died a violent death. He was beheaded;
it seemed the only fitting way for one of that family to take his
departure from life. The Pizarros used to behead their victims and
then show themselves conspicuously at the funeral. When it came
their turn to die, they were treated with scantier courtesy.
Philip the Second was Prescott’s most ambitious work. Though
but a fragment, the fragment is of noble dimensions, being longer by
many pages than the Ferdinand and Isabella. The narrative is
extraordinarily vivid. Few pages can match for interest those in which
are described Philip’s coming to Flanders and his assumption of
power at the hands of his father Charles the Fifth. Here are exhibited
at their best the much-praised qualities of Prescott’s style. His prose
grew better as he grew older.
The characters stand out like the figures of a play: the great
princes, Charles the Fifth, Philip, Mary of England, and Elizabeth; the
great warriors and statesmen, Guise, Montmorency, Alva, Egmont,
and William of Orange; noble ladies like Margaret of Parma and the
beautiful Elizabeth of France. The events were of high and tragic
importance, for during this reign was to be settled the great question
of freedom of thought and the right to worship God as the
conscience and the reason dictated. The very contrasts of costume
came to the aid of the historian in dealing with this romantic age. It
would seem as if the writer must be picturesque in spite of himself.
The modern reader, whatever be his natural bent, finds himself
impelled by the critical spirit of the times into distrusting all history
which is not technical and hard to grasp. Prescott’s books are
incorrigibly ‘literary’ and therefore more or less under suspicion.
Because they are attractive, it is taken for granted that they are
unsound. Certain unhappy beings have gone so far as to slander
them outright by calling them romances. But this is mere impatience
with the kind of historical writing which Prescott’s work exemplifies.
He was a master of the art of narrative; and history which stops with
narrative is in the minds of severe students little better than the more
vicious forms of literary idleness, such as poetry and fiction. Prescott
gratifies his reader’s curiosity about the past, but is not over
solicitous to ‘modify his view of the present and his forecast of the
future.’ In other words, he is well content to look at the surface of
history, leaving it to others to look below the surface and
philosophize on what they find there.
Nevertheless these brilliant volumes have a value which is
something more than literary even if it be a good deal less than
scientific. It is perhaps not extravagant to pronounce them an
indispensable propædeutic to the study of Spanish-American history.
They cannot be displaced by works which ‘go much deeper into the
subject.’ Depth is not what is at all times most needed. We need
stimulus, and encouragement to face the discipline awaiting us in
deep books. He who, having read Prescott, was content to read no
farther would be an odd sort of student; but not so odd as he who
labored under the impression that Prescott was a historian whom he
could afford to do without.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like