Download full Mastering PHP design patterns develop robust and reusable code using a multitude of design patterns for PHP 7 Ali ebook all chapters
Download full Mastering PHP design patterns develop robust and reusable code using a multitude of design patterns for PHP 7 Ali ebook all chapters
com
https://textbookfull.com/product/mastering-php-
design-patterns-develop-robust-and-reusable-code-
using-a-multitude-of-design-patterns-for-
php-7-ali/
https://textbookfull.com/product/design-patterns-in-php-and-
laravel-1st-edition-kelt-dockins/
textbookfull.com
https://textbookfull.com/product/friends-and-lovers-how-to-create-the-
relationships-you-want-marc-allen/
textbookfull.com
Irène Némirovsky's Russian Influences: Tolstoy, Dostoevsky
and Chekhov 1st Edition Marta Laura Cenedese
https://textbookfull.com/product/irene-nemirovskys-russian-influences-
tolstoy-dostoevsky-and-chekhov-1st-edition-marta-laura-cenedese/
textbookfull.com
https://textbookfull.com/product/wall-street-journal-wednesday-
march-25-2020-news-corp/
textbookfull.com
https://textbookfull.com/product/the-cambridge-handbook-of-
morphology-1st-edition-andrew-hippisley/
textbookfull.com
https://textbookfull.com/product/algorithmic-trading-with-interactive-
brokers-python-and-c-1st-edition-matthew-scarpino/
textbookfull.com
https://textbookfull.com/product/technological-interventions-in-
management-of-irrigated-agriculture-1st-edition-megh-r-goyal/
textbookfull.com
Grayson The Kings of Brighton 3 1st Edition Megyn Ward
https://textbookfull.com/product/grayson-the-kings-of-brighton-3-1st-
edition-megyn-ward/
textbookfull.com
Mastering PHP Design Patterns
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.
Livery Place
35 Livery Street
ISBN 978-1-78588-713-0
www.packtpub.com
Credits
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 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 ]
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
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.
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 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.
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.
[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".
[4]
Preface
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."
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.
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.
[5]
Preface
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:
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
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.
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.
“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.
“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.
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]
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
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?”.
[ 10 ]
Why "Good PHP Developer" Isnt an Oxymoron
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.
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.
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;
}
}
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;
}
}
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
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;
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 ]
Random documents with unrelated
content Scribd suggests to you:
placed in the garden, surrounded by a profusion of Ladies’ Delights, in
memory of the lost friend.
It was a fixed principle with Mr. Vernon that no man had a right to live
in the world without doing his share of its work. He imported seeds and
scions, which he planted and grafted himself, always distributing a liberal
portion among his neighbours. “My fruit and vegetables will soon
command a ready sale in the city market,” said he; “but the proceeds shall
go toward a school-fund, and the establishment of a Lyceum. I do not desire
that our children should inherit great wealth. Life sufficiently abounds with
dangers and temptations, physical and mental, without adding that glittering
snare for their manhood and womanhood. The wisest and kindest thing we
can do for them is to educate equally themselves and the people among
whom they are to live.”
“There spoke the same generous soul that chose the poor country-girl for
a wife!” she exclaimed, “What can I ever do to prove the gratitude I feel?”
Playfully he put his hand over her mouth, to stop that self-depreciation.
They remained silent for a while, seated on the grassy slope, looking out
upon the winding river and the noble trees. “How much this scene
resembles the parks and lawns of old England,” said the happy bride. “If it
were not for the deep stillness, and the absence of human habitations, I
could almost imagine myself in my native land.”
“I like it better than English parks and lawns, for two reasons,” he
replied. “I prefer it, because it is formed by Nature, and not by Art; and
Nature gives even to her quietest pictures peculiar touches of wild
inimitable grace. Still more does the scene please me, because these broad
acres are not entailed upon noblemen, who cannot ride over their estates in
a week, while their poor tenantry toil through life without being allowed to
obtain possession of a rood of land.”
Sibella looked at him with affectionate admiration, while she replied,
“Truly, ‘the child is father of the man.’ There spoke the same soul that
invited a tradesman’s manly son to spend the vacation with him, in
preference to Lord Smallsoul.”
“I will never reprove my boy, if he brings home the manly son of a
wood-sawyer to spend his school vacations with us,” rejoined he. “But
hark! Hear our children laughing and shouting! What sound is more musical
than the happy voices of children? See the dear little rogues racing over the
carpet of wild-flowers! How they seem to love each other! God be praised,
they are free to enact the parts of Paul and Virginia in this lovely solitude.
May no rich relatives tempt them into fashionable life, and make shipwreck
of their happiness.”
A SERENADE.
Peter Barker belonged to that numerous class, who are neither better
nor worse than other men. Left an orphan in his infancy, the paths of life
were rough and lonely at the outset. He had a violent temper and a good
heart. The first was often roused into activity, and punished with energy
kindred to its own; the last remained almost undeveloped, for want of genial
circumstances and reciprocated affection. One softening gleam fell upon his
early path, and he loved it like the sunshine, without comprehending the
great law of attraction that made it so very pleasant. When he attended
school in the winter months, he always walked home with a little girl
named Mary Williams. On the play-ground he was with her, always ready
to do battle with anybody who disobliged her. Their comrades laughed, and
called him Mary’s beau; and they blushed and felt awkward, though they
had no idea what courting meant. Things had arrived at this state of half-
revealed consciousness, he being fourteen years old, and Mary twelve,
when her friends removed to the West, and the warm, bright influence
passed out of his life. He never rightly knew whether he was in love with
Mary; but years afterwards, when people talked to him about marrying, he
thought of her, wondering where she was, and whether she remembered
him. When he drove his cows home from pasture, the blackberry bushes on
the way brought up visions of his favourite school-mate, with her clean
cape-bonnet thrown back, her glossy brown hair playing with the winds,
and her innocent face smiling upon him with friendly greeting. “She was
the best and prettiest child I ever saw,” he often said to himself; “I wonder
whether she would be as pleasant now.” Sometimes he thought of going to
the West and seeking her out. But he knew not where to find her; his funds
were small, and his courage fell at the thought; “Oh, it is many years ago
since we were children together. Perhaps I should find her married.”
Gradually this one ray of poetry faded out of his soul, and all his thoughts
fell into the common prosaic mould. His lot was cast with rough people,
who required much work, and gave little sympathy. The image of his little
mate floated farther and farther away, and more and more seldom her clear
blue eyes smiled upon him through the rainbow-mists of the past, or from
the air-castles of the future. In process of time, he married, after the same
fashion that a large proportion of men do; because it was convenient to have
a wife, and there was a woman of good character in the neighbourhood,
willing to marry whoever first offered her a respectable home. Her character
bore the stamp of harmless mediocrity. She was industrious and patient, but
ignorant, dull, and quietly obstinate. The neighbours said she was well
suited to him, he was so rough and passionate; and in the main he thought
so himself; though her imperturbable calmness sometimes fretted him, as a
rock chafes the lashing ocean into foam. The child that was born to them,
they both loved better than they had ever loved; and according to their light,
they sincerely strove to do their duty. His bodily wants were well supplied,
often at the cost of great weariness and self-sacrifice; but their own rude
training had given them few good ideas concerning the culture of an
immortal soul. The infant did more for them, than they for him. Angelic
influences, unseen and unheard amid the hard struggles of their outward
life, became visible and audible through the unconscious innocence of their
little one. For the second time in his life, a vision of beauty and love
gleamed across the rugged path of that honest, laborious man. Vague
impressions of beauty he had constantly received from the great panorama
of the universe. His heart sometimes welcomed a bright flower in the
sunshine, or a cluster of lilies on the stream; he marvelled at the splendor of
the rainbow, and sometimes gazed reverently at the sun sinking to rest in his
rich drapery of purple and gold. But these were glimpses of the Infinite;
their beauty did not seem to appertain to him; it did not enter like a magic
charm into the sphere of his own existence, as did the vision of Mary
Williams and his own little Joe. The dormant tenderness there was in him
leaped up at the smile of his babe, and every pressure of the little fingers
made a dimple in the father’s heart. Like the outbursts of spring, after a long
cold winter, was this revelation of infancy to him. When he plodded home,
after a hard day’s work, it rested him body and soul to have the little one
spring into his arms for a kiss, or come toddling along, tilting his little
porringer of milk, in eagerness to eat his supper on father’s knee.
But though this new influence seemed to have an almost miraculous
power over his nature, it could not quite subdue the force of temperament
and habit. As the darling babe grew into boyhood, he was sometimes
cherished with injudicious fondness, and sometimes repelled by bursts of
passion, that made him run and hide himself from the over-indulgent father.
Mr. Barker had himself been educated under the dispensation of
punishment, rather than attraction, and he believed in it most firmly. If his
son committed a fault, he thought of no other cure than severity. If a
neighbour did him an ill turn, he would observe, in presence of the boy, “I
will watch my chance to pay him for it.” If the dog stole their dinner, when
they were at work in the woods, he would say, “Run after him, Joe, and give
the rascal a sound beating.” When he saw the child fighting with some
larger lad, who had offended him, he would praise his strength and courage,
and tell him never to put up with an insult. He was not aware that all these
things were education, and doing far more to form his son’s character than
any thing he learned at school. He did not know it, because his thoughts had
never been directed toward it. The only moral instruction he had ever
received, had been from the minister of the parish; and he usually preached
about the hardheartedness of Jews two thousand years ago, rather than the
errors and temptations of men and boys, who sat before him.
Once he received an admonition from his neighbour Goodwin, which,
being novel and unexpected, offended him, as an impertinent interference
with his rights. He was riding home with Joe, then a lad of thirteen, when
the horse took fright at a piece of white paper, that the wind blew across the
road. Mr. Barker was previously in an ill humor, because a sudden squall of
rain had wet some fine hay, all ready for the barn. Pursuing the system on
which he had himself been educated, he sprang to the ground and cudgelled
the poor beast unmercifully. Mr. Goodwin, who was passing by, inquired
the cause of so much severity, and remonstrated against it; assuring him that
a horse was never cured of bad habits by violence. He spoke mildly, but Mr.
Barker was irritated, and having told him to mind his own business, he
continued to whip the poor frightened animal. The humane neighbour
turned away, saying, “That is a bad lesson for your son, Mr. Barker.”
“If you say much more, I will flog you, instead of the horse,” muttered
the angry man. “It is’nt his horse. What business is it to him?” he added,
turning to his son.
He did not reflect in what a narrow circuit he was nailing up the
sympathies of his child, by such words as those. But when he was reseated
in the wagon, he did not feel altogether pleased with himself, and his
inward uneasiness was expended on the horse. The poor bewildered animal,
covered with foam, and breathing short and hard, tried his utmost to do his
master’s will, as far as he could understand it. But, nervous and terrified,
constantly in expectation of the whip, he started at every sound. If he went
too fast, he was reined in with a sudden jerk, that tore the corners of his
mouth; if he went too slow, the cruel crack of the whip made him tear over
the ground, to be again restrained by the violent jerk.
The sun was setting, and threw a radiant glow on every tree and little
shrub, jewelled by the recent shower. Cows grazed peacefully in verdant
hollows; birds sang; a little brook rippled cosily by the wayside; winds
played gently with the flowers, and kissed the raindrops from their faces.
But all this loveliness passed unheeded by those human hearts, because they
had at the moment no inward beauty to harmonize with nature. Perhaps the
familiar landscape seemed quite otherwise to the poor horse, than it would
have done, had he travelled along those pleasant paths guided by a wise and
gentle hand.
Had Joseph continued to be little Joe, his eager welcome and loving
prattle might soon have tamed the evil spirit in his father’s soul that night.
But he was a tall lad, who had learned to double up his fists, and tell other
boys they had better let him alone, if they knew what was good for
themselves. He still loved his father better than any thing else in the world,
but the charm and the power of infancy were gone. He reflected back the
vexed spirit, like a too faithful mirror. He was no longer a transparent,
unconscious medium for the influence of angels.
Indeed, paternal affection gradually became a hardening, rather than a
softening influence. Ambition for his son increased the love of
accumulation; and the gratification of this propensity narrowed his
sympathies more and more. Joseph had within him the unexpanded germs
of some noble qualities; but he inherited his father’s passionate
temperament with his mother’s obstinacy; and the education of such
circumstances as I have described turned his energies and feelings into
wrong channels. The remark, “It is’nt his horse; what business is it to him?”
heard in his boyhood, expressed the views and habits of his later years. But
his mental growth, such as it was, pleased his father, who often said
exultingly, “There is no danger of Joe. He knows how to fight his own way
through the world.”
Such was their mutual product of character, when Mr. Barker was
summoned to a jury, in a case involving life or death. He was vexed to be
called away from his employments, and had never reflected at all upon the
fearful responsibility of a juryman. James Lloyd, the prisoner, was a very
young man, and his open, honest countenance gave no indication of
capacity for crime; but he was accused of murder, and circumstantial
evidence was strong against him. It was proved that a previous quarrel had
existed between him and the murdered man; and that they had been seen to
take the same road, the prisoner in a state of intoxication, the night the
violent deed was committed. Most people thought there was no doubt of his
guilt; others deemed the case by no means certain. Two of the jury were
reluctant to convict him, and wished to find the evidence insufficient; the
penalty was so dreadful, and their feelings were so much touched by the
settled misery of his youthful countenance. Others talked sternly of justice,
and urged that the Scripture demanded blood for blood. Of this number was
Peter Barker. From the beginning, he was against the prisoner. The lawyer
who pleaded for him had once been employed in a law-suit against Mr.
Barker, and had gained the cause for his client. The juryman cherished a
grudge against him for his sarcastic eloquence on that occasion. Moreover,
it so happened that neighbour Goodwin, who years ago had reproved his
severity to the horse, took compassionate interest in the accused. He often
consulted with his lawyer, and seemed to watch the countenances of the
jury anxiously. It was a busy season of the year, and the jury were impatient
to be at their workshops and farms. Mr. Barker would not have admitted it,
even to himself, but all these circumstances helped to increase his hardness
against the prisoner. By such inconceivably slight motives is the conduct of
men often swayed on the most important occasions.
“If the poor young fellow really did commit the act,” said one of the
jury, “it seems likely that he did it in a state of intoxication. I was once
drunk myself; and they told me afterward that I had quarrelled with a man,
and knocked him down a high flight of steps; but I had no recollection of it.
If I had killed him, and they had hung me for it, what an awful thing it
would have been for my poor father and mother. It taught me a good lesson,
for I was never again intoxicated. Perhaps this poor youth might profit by
his dreadful experience, if a chance were allowed him. He is so young! and
there is nothing bad in his countenance.”
“As for his womanly face,” replied Mr. Barker, “there is no trusting to
that. The worst villains are not always the worst-looking. As for his being
intoxicated, there is no telling whether it is true or not. That cunning lawyer
may have made up the story, for the sake of exciting compassion; and the
witnesses may be more than willing enough to believe every thing strange
in the prisoner’s conduct was the result of intoxication. Moreover, it won’t
do to admit that plea in extenuation; for then, don’t you see, a man who
wants to kill his enemy has only to get drunk in the first place? If anybody
killed my Joe, drunk or not drunk, I should want him to swing for it.”
By such remarks, urged in his vehement way, he swayed minds more
timid and lenient than his own, without being fully aware of what he was
doing. He was foreman of the jury; and when the awful moment arrived on
which depended the life of a fellow being, he pronounced the word
“Guilty,” in a strong, firm voice. The next instant his eye fell on the
prisoner, standing there so pale, and still, looking at him with such fixed
despair. There was something in the face that moved him strongly. He
turned quickly away, but the vision was before him; always, and
everywhere before him. “This is weakness,” he said to himself. “I have
merely done my duty. The law required it. I have done my duty.” But still
the pale young face looked at him; always, and everywhere, it looked at
him.
He feared to touch a newspaper, for he wished not to know when the day
of execution would arrive. But officious neighbours, ignorant of his state of
mind, were eager to talk upon the subject; and when drawn into such
discourse, he strove to fortify his own feelings by dwelling on all the worst
circumstances of the case. Notwithstanding all his efforts, the night
preceding the execution, he had troubled dreams, in which that ghastly
young face was always conspicuous. When he woke, he saw it in the air. It
walked beside him as he ploughed the fields, it stood before him on the
threshold of his own door. All that the merciful juryman had suggested
came before him with painful distinctness. Could there be a doubt that the
condemned had really committed murder? Was he intoxicated? Might he
have happened to be intoxicated for the first time in his life? And he so
young! But he drove these thoughts away; saying ever to himself, “The law
required it. I merely did my duty.” Still every thing looked gloomy to him.
The evening clouds seemed like funeral palls, and a pale despairing face
gazed at him forever.
For the first time in his manhood, he craved a companion in the
darkness. Neighbours came in, and described the execution; and while they
talked, the agitated juryman beat the fire-brands into a thousand pieces, and
spoke never a word. They told how the youth had written a long letter to his
mother, and had died calm and resigned. “By the way, perhaps you knew
his mother, Mr. Barker,” said one; “they tell me she used to live in this
neighbourhood. Do you remember a girl by the name of Mary Williams?”
The tongs dropped from Mr. Barker’s hand, as he gasped out, “Mary
Williams! Was he her son? God forgive me! Was he her son?” And the
strong man laid his head upon the table and wept.
There was silence in the room. At last, the loquacious neighbour said, in
a subdued tone, “I am sorry I hurt your feelings. I didn’t know she was a
friend of yours.”
The troubled juryman rose hastily, walked to the window, looked out at
the stars, and, clearing his choked voice, said, “It is many years since I
knew her. But she was a good-tempered, pretty girl; and it seems but
yesterday that we used to go together to pick our baskets full of berries. And
so she was his mother? I remember now there was something in his eye that
seemed familiar to me.”
Perhaps the mention of Mary’s beauty, or the melting mood, so unusual
with her husband, might have excited a vague feeling of jealousy in Mrs.
Barker. Whatever might have been the motive, she said, in her demure way,
without raising her eyes from her knitting, “Well, it was natural enough to
suppose the young man had a mother; and other mothers are likely to have
hearts that can feel, as well as this Mary Williams.”
He only answered by shaking his head slowly, and repeating, as if to
himself, “Poor Mary! and so he was her son.”
Joseph came in, and the details of the dreadful scene were repeated and
dwelt upon, as human beings are prone to dwell on all that excites strong
emotion. To him the name of Mary Williams conjured up no smiling visions
of juvenile love; and he strove to fortify his father’s relenting feelings, by
placing in a strong light all the arguments in favour of the prisoner’s guilt.
The juryman was glad to be thus fortified, and replied in a firm, reassured
voice, “At all events, I did my duty.” Yet, for months after, the pale young
face looked at him despairingly from the evening air, and came between
him and the sunshine. But time, which softens all things, drifted the dreary
spectre into dim distance; and Mr. Barker’s faculties were again completely
absorbed in making money for his son.
Joseph was called a fine, promising young man; but his conduct was not
altogether satisfactory to his parents. He was fond of dress and company,
and his impetuous temperament not unfrequently involved him in quarrels.
On two or three of these occasions, they feared he had been a little excited
by drink. But he was, in reality, a good-hearted fellow, and, like his rough
father, had undeveloped germs of deep tenderness within him. His father’s
life was bound up within his; his mother loved him with all the energy of
which her sluggish nature was capable; and notwithstanding the inequalities
of his violent and capricious temper, the neighbours loved him also.
What, then, was their consternation, when it was rumoured that on his
twenty-fourth birth-day he had been arrested for murder! And, alas! it was
too true that his passions had thus far over-mastered his reason. He wished
to please a young girl in the vicinity; and she treated him coolly, because a
rival had informed her that he was seen intoxicated, and in that state had
spoken over-boldly of being sure of her love. He drank again, to drown his
vexation; and while the excitement of the draught was on him, he met the
man who informed against him. His exulting rival was injudicious enough
to exclaim, “Ho! here you are, drunk again! What a promising fellow for a
husband!” Unfortunately, an axe was at hand, and, in the double fury of
drink and rage, he struck with it again and again. One hour after, he would
have given all he ever hoped to possess, nay, he would gladly have died,
could he have restored the life he had so wantonly destroyed.
Thus, Mr. Barker was again brought into a court of justice on an affair of
life and death. How differently all questions connected with the subject
presented themselves now! As he sat beside that darling son, the pride of his
life, his only hope on earth, oh, how he longed for words of fire, to plead
that his young existence might be spared for repentance and amendment!
How well he remembered the juryman’s plea for youth and intoxication!
and with what an agony of self-reproach he recalled his own hard answer!
With intense anxiety he watched the countenance of the jury for some
gleams of compassion; but ever and anon, a pale young face loomed up
between him and them, and gazed at him with fixed despair. The vision of
other years returned to haunt him; and Joseph, his best beloved, his only
one, stood beside it, pale and handcuffed, as he had been. The voice that
pronounced his son guilty sounded like an awful echo of his own; and he
seemed to hear Mary Williams whisper, “And my son also was very young.”
That vigorous off-shoot from his own existence, so full of life and
feeling, and, alas, of passion, which misguides us all—he must die! No
earthly power can save him. May the All Merciful sustain that poor
father, as he watches the heavy slumber of his only son in that dark prison;
and while he clasps the cold hand, remembers so well the dimpled fingers
he used to hold in his, when little Joe sat upon his knee and prattled childish
love.
And the All Merciful was with him, and sent influences to sustain him
through that terrible agony. It did not break his heart; it melted and subdued
him. The congealed sympathies of his nature flowed under this ordeal of
fire; and, for the first time, he had a realizing sense that every human being
is, or has been, somebody’s little Joe.
“How kind you are to me!” said the prisoner, in answer to his soothing
words and affectionate attentions.
He replied meekly, “Would I had always been so!” Then turning his face
away, and earnestly pressing Joseph’s hand, he said, in an agitated voice,
“Tell me truly, my son, does it ever occur to you, that I may have been to
blame for this great misfortune that has befallen you?”
“You, dear father!” he exclaimed. “I do not understand what you mean.”
Still keeping his face turned away, and speaking with effort, Mr. Barker
said, “Do you remember once, when I was beating my horse cruelly, (you
were a boy of twelve then) neighbour Goodwin remarked to me, that I was
giving a bad lesson to my son? I was angry with him at the time; and
perhaps that resentment helped to make me hard toward a poor young
fellow who is dead and gone; but his words keep ringing in my ears now.
May God, in his mercy, forgive me, if I have ever done or said any thing to
lead you into this great sin! Tell me, Joseph, do you ever think it might have
happened otherwise, if you had had a less violent father?”
“My poor father!” exclaimed the prisoner, pressing his hand
convulsively, “it almost breaks my heart to hear you thus humble yourself
before me, who so little deserve it at your hands. Only forgive me my
violent outbreaks, dear father! for in the midst of them all, I always loved
you. You have always sought to do me good, and would rather have died,
than have led me into any harm. But since I have been here in prison, I have
thought of many things, that never occurred to me before. The world and all
things in it are placed before me in a different light. It seems to me men are
all wrong in their habits and teachings. I see now that retaliation and hatred
are murder. I have read often, of late, the exhortation of Jesus to forgive our
brother his offences, not only seven times, but seventy times seven; and I
feel that thus it ought to be with human beings in all their relations with
each other. What I have done cannot be undone; but if it will be any
satisfaction to you, rest assured that I did not intend to kill him. I was
wretched, and I was fool enough to drink; and then I knew not what I did.
Violent as my temper has been, I never conceived the thought of taking his
life.”
“I know it, my son; I know it,” he said; “and that reflection consoles me
in some degree. While I have a loaf of bread, I will share it with the mother
and sister of him you——” he hesitated, shuddered, and added in a low
deep tone—“you murdered.”
“I was going to ask that of you,” replied the prisoner; “and one thing
more, dear father; try to bear up bravely under this terrible blow, for the
sake of my poor patient mother.”
“I will, I will,” he answered; “and now my dear misguided boy, say you
forgive your poor father for the teachings of his violent words and actions. I
did not foresee the consequences, my child. I did it in my ignorance. But it
was wrong, wrong, all wrong.”
The young man threw himself on his father’s bosom, and they had no
other utterance but tears.
* * * * *
After his only strong link to life was broken by the violent arm of the
law, Mr. Barker was a changed man; silent, and melancholy, patient, gentle,
and forgiving to all. He never complained of the great sorrow that wasted
away his life; but the neighbours saw how thin and sad he looked, and the
roughest natures felt compassion for him.
Every year, she who had been Mary Williams received a hundred dollar
note. He never whispered to any mortal that it was sent by the juryman who
helped to condemn her son to death; but when he died, a legacy of a
thousand dollars to her showed that he never forgot the pale despairing face,
that for years had haunted his dreams.
THE FAIRY FRIEND.
In these rational days, most people suppose that fairies do not exist; but
they are mistaken. The mere fact that fairies have been imagined proves that
there are fairies; for fancy, in her oddest freaks, never paints any thing
which has no existence. She merely puts invisible agencies into visible
forms, and embodies spiritual influences in material facts. It seems a wild
fiction when we read of beautiful young maidens floating in gossamer, and
radiant with jewels, who suddenly change into mocking old hags, or jump
off into some slimy pool, in the form of a frog; or like the fair Melusina,
doomed to become a fish on certain days of the year, and those who
happened to see her in that plight could never again see her as the Fair
Melusina. Yet who that has grown from youth to manhood, who that has
been in love and out of love, has not found the fairies of his life playing him
just such tricks?
In the fascinating ballet of Giselle, so poetic in conception, and so
gracefully expressed in music, there is deep and tender meaning for all who
have lived long, or lived much. Is not Memory a fairy spirit, like Giselle,
dancing round graves, hovering between us and the stars, flitting across our
woodland rambles, throwing us garlands and love-tokens from the past,
coming to us in dreams, so real that we clasp our loved ones, and gliding
away when morning gleams on the material world?
Oh yes there are fairies, both good and bad; and they are with us
according as we obey or disobey their laws of being. One, with whom I
made acquaintance as soon as I could run alone, has visited me ever since;
though sometimes she pouts and hides herself, and will not soon come
back. I am always sad when she is gone; for she is a wonder-working little
sprite, and she takes all my wealth away with her. If you were to gaze on a
field of dandelions, if she were not at your elbow, you would merely think
they were pretty posies, and would make excellent greens for dinner. But if
she touches you, and renders you clairvoyant, they will surprise you with
their golden beauty, and every blossom will radiate a halo. Sometimes she
fills the whole air with rainbows, as if Nature were out for a dance, with all
her ribbons on. A sup of water, taken from a little brook, in the hollow of
her hand, has made me more merry than would a goblet of wine. She has
often filled my apron with opals, emeralds, and sapphires, and I was never
weary of looking at them; but those who had wandered away from the fairy,
and forgotten her treasures, sneered at my joy, and said, “Fie upon thee!
Wilt thou always be a child? They are nothing but pebbles.”
Last Spring, my friendly little one guided me to a silver-voiced waterfall
at Weehawken, where a group of German forget-me-nots were sitting with
their feet in the water. Their little blue eyes laughed when they saw me. I
asked what made them smile in my face so lovingly. They answered,
“Because we hear a pleasant song, and you know what it says to us.” It was
not I who knew; it was the fairy; but she had magnetized me, and so I heard
all that was said to her.
A wealthy invalid passed by, afflicted with dyspepsia. He did not see the
flowers smile, or hear the waterfall singing his flowing melody of love to
the blue eyes that made his home so beautiful. He had parted from the fairy
long ago. He told her she was a fool, and that none would ever grow rich,
who suffered themselves to be led by her. She laughed and said, “Thou dost
not know that I alone am rich; always, and every where, rich. But go thy
ways, vain worldling. Shouldst thou come back to me, I will ask if thou hast
ever found any thing equal to my gems and rainbows.” She gazed after him
for a moment, and laughed again, as she exclaimed, “Aha, let him try!”
The gay little spirit spoke truly; for indeed there is nothing so real as her
unrealities. Those who have parted from her complain that she made them
large promises in their early time, and has never kept them; but to those
who remain with her trustfully, she more than fulfils all. For them she
covers the moss-grown rock with gold, and fills the wintry air with
diamonds. It is many years since she first began to tell me her fine stories.
But this very last New Year’s day she led me out into the country, and
lighted up all the landscape as I went, so that it seemed lovelier than the
rarest pictures. The round bright face of the moon smiled at me, and said, “I
know thee well. Thou hast built many castles up here. Come to them
whenever thou wilt. Their rose-coloured drapery, with rainbow fringes, is
more real than silken festoons in Broadway palaces.” I was glad at heart,
and I said to my fairy, “The sheriff cannot attach our furniture, or sell our
castles at auction.” “No indeed,” she replied. “He cannot even see them. He
has forgotten me. He thinks all the gems I show are only pebbles, and all
my prismatic mantles mere soap-bubbles.”
This simple little sprite says much richer things than the miracles she
does. Her talk is all alive. She is a poet, though she knows it not; or, rather
because she knows it not. She tells me the oddest and most brilliant things;
and sometimes I write them down imperfectly, as well as I can remember
them. Matter-of-fact persons shake their heads, and say, “What on earth
does the woman mean? I never see and hear such things.” And grave people
raise their spectacles and inquire, “Can you point me out any moral, or any
use, in all this stuff?” “There is no sense in it,” says one; “The writer is
insane,” says another; “She’s an enthusiast, but we must pardon that
weakness,” says a third, more magnanimous than others. The fairy and I
have great fun together, while we listen to their jokes and apologies. The
frolicsome little witch knows very well that it is she who says the things
that puzzle them; and she knows the meaning very well; but she never tells
it to those who “speer questions.”
She is a philosopher, too, as well as a poet, without being aware of it.
She babbles all manner of secrets, without knowing that they are secrets. If
you were to propound to her a theory concerning the relation between tones
and colours, she would fold her wings over her face and drop asleep. But
sound a flute, and she will leap up and exclaim, “Hear that beautiful, bright
azure sound!” And if oboës strike in, she will smile all over, and say, “Now
the yellow flowers are singing. How pert and naïve they are!” It was she
who led the little English girl to the piano, and put a melody of cowslip
meadows in her brain; and as the child improvised, she smiled, and said
ever to herself, “This is the tune with the golden spots.”
But this genial little fairy is easily grieved and estranged. Her
movements are impulsive, she abhors calculators, and allows no questions.
If she shows you a shining gem, be careful not to inquire what would be its
price in the market; otherwise its lustre will fade instantly, and you will
have to ask others whether the thing you hold in your hand has any beauty
or value. If she beckons into blooming paths, follow her in simple faith,
whether she leads to castles in the moon, or lifts up a coverlet of leaves to
peep at little floral spirits sound asleep, with their arms twined round the
fragrant blossoms of the arbutus. She carries with her Aladdin’s lamp, and
all the things she looks upon are luminous with transfigured glory. Take
heed not to inquire where the path will lead to, whether others are
accustomed to walk in it, or whether they will believe your report of its
wonderful beauty. Above all, be careful not to wish that such visions may
be kept from the souls of others, that your own riches may seem marvellous
and peculiar. Wish this but for a single instant and you will find yourself all
alone, in cold gray woods, where owls hoot, and spectral shadows seem to
lie in wait for you. But if with a full heart you crave forgiveness for the
selfish thought, and pray earnestly that the divine Spirit of Beauty may be
revealed to all, and not one single child of God be excluded from the radiant
palace, then will the fairy come to you again, and say, “Now thou and I are
friends again. Give me thy hand, and I will lead thee into gardens of
paradise. Because thou hast not wished to shut up any thing, therefore thou
shalt possess all things.” Instantly the cold gray woods shine through a veil
of gold; the shadows dance, and all the little birds sing, “Joy be with thee.”
A spirit nods welcome to you from every cluster of dried grass; a soul
beams through the commonest pebble; ferns bow before you more
gracefully than the plumes of princes; and verdant mosses kiss your feet
more softly than the richest velvets of Genoa.
Trust the good little fairy. Be not disturbed by the mockery of those who
despise her simple joys. She said truly, “I alone am rich; always, and
everywhere, rich.”
WERGELAND, THE POET.
Wergeland was one of the most popular poets Norway has ever
produced. He rhymed with wonderful facility, and sometimes, when a rush
of inspiration came upon him, he would write verses during a whole day
and night, with untiring rapidity, scarcely pausing to eat, or to rest his hand.
In the poems which expressed his own inward life there was often
something above common comprehension; but, in addition to those higher
efforts, he wrote a great number of verses for the peasantry, in all the
peculiar dialects of their various districts. The merest trifle that flowed from
his pen is said to have contained some sparkling fancy, or some breathing of
sentiments truly poetic. He was an impassioned lover of nature, and in his
descriptions of natural objects was peculiar for making them seem alive.
Thus in one of his poems he describes the winds coming through clefts of
rock, forming a powerful current in the fiord, driving white-crested waves
before them, like a flock of huge storm-birds. A lawyer, who passes through
the current in a boat, imagines the great waves to be angry spectres of the
many poor clients whom he has wronged. He throws one ten dollars,
another twenty, another fifty, to pacify them. At last, a wondrous tall wave
stretches forth his long neck, as if to swallow him. The terrified lawyer
throws him a hundred dollars, imploring him to be merciful. Just then, the
boat turns a corner of the rock, out of the current. The great wave eagerly
bends his long arm round the rock, and tries to clutch him; then retreats,
disappointed at his escape.
Wergeland had a strongly marked head, full of indentations, like a bold
rocky shore. He was an athletic, earnest, jovial man, and enjoyed life with a
keen zest. His manner of telling a story was inimitably funny and vivacious.
While he was settling his spectacles, before he began to speak, a smile
would go mantling all over the lower part of his face, announcing that
something good was coming. His soul went forth with warm
spontaneousness to meet all forms of being; and this lively sympathy
seemed to attract both men and animals toward him magnetically. He was
accustomed to saddle his own horse, which stood loose in the barn, among
pet rabbits, pet pigeons, pet birds, all sorts of poultry, and a favourite cat.
These creatures all lived in the greatest friendship together. They knew their
master’s voice perfectly well; and the moment he opened the door, they
would all come neighing, purring, cooing, singing, crowing, capering and
fluttering about him. His cottage was a picturesque place, ornamented with
all sorts of mosses, vines, and flowers. Under it was a grotto made of rocks
and shells, in which were an old hermit, with a long beard, and various
other grotesque figures, carved in wood. The grotto was occasionally
lighted up in the evening, and the images, seen among flickering shadows,
excited great awe in the minds of peasant children.
This gifted and genial man, who lived in such loving companionship
with nature, was called away from the earth, which seemed to him so
cheerful, before he had passed the middle term of human life. The news of
his death was received with lamentation by all classes in Norway. Crowds
of people went to Christiana to bid farewell to the lifeless body of their
favorite poet. While in the last stage of consumption, in May, 1845, he
wrote the following verses, which were read to me by one of his
countrymen, who translated them literally, as he went along. Even through
this imperfect medium, my heart was deeply touched by their childlike
simplicity and farewell sadness. The plaintive voice seemed to become my
own, and uttered itself thus, in English rhyme, which faithfully preserves
the sense of the original:
SUPPLICATION TO SPRING.
Oh, save me, save me, gentle Spring!
Bring healing on thy balmy wing!
I loved thee more than all the year.
To no one hast thou been more dear.
The following lines, written two days before he died, were addressed to
a fragrant, golden-coloured flower whose English name I cannot ascertain.
TO THE GULDENLAK.
On their little heaps of straw, brother and sister slept soundly in each other’s
arms; and if the hooting of an owl chanced to wake them, some bright star
looked in with friendly eye, through chinks in the walls, and said, “Go to
sleep, little ones; for all little children are dear to the good God.”
Thus, with scanty food and coarse clothes, plenty of pure air and blue
sky, Fritz and his sister went hand in hand over their rugged but flower-
strewn path of life, till he was nearly seven years old. Then came Uncle
Heinrich, his mother’s brother, and said the boy could be useful to him at
the mill, where he worked; and if the parents were willing to bind him to his
service, he would supply him with food and clothing, and give him an outfit
when he came of age. Tears were in Liesbet’s eyes; for she thought how
lonely it would seem to her and little Gretchen, when they should no longer
hear Fritz mocking the birds, or singing aloud to the high heaven. But they
were very poor, and the child must earn his bread. So, with much sorrow to
part with father and mother, and Gretchen, the goat and the stork, and with
some gladness to go to new scenes, Fritz departed from the old nest that had
served him for a home. Mounted with Uncle Heinrich, on the miller’s
donkey, he ambled along through rocky paths, by deep ravines and castle-
crowned hills, with here and there glimpses of the noble river, flowing on,
bright and strong, reflecting images of spires, cottages, and vine-covered
slopes. When he arrived at his new home, the good grandmother gave him
right friendly welcome, and promised to set up on her knitting-needles a
striped blue cap for him to wear. Uncle Heinrich was kind, in his rough
way; but he thought it an excellent plan for boys to eat little and work hard.
Fritz, remembering the blossom-carpet of the old castle, was always
delighted to spy a clump of flowers. His uncle told him they looked well
enough, but he wondered anybody should ever plant them, since they were
not useful either to eat or wear; and that when he grew older, he would
doubtless think more of pence than posies. Thus the child began to be
ashamed, as of something wrong, when he was caught digging a flower. But
his laborious and economical relative taught him many orderly and thrifty
ways, which afterward had great influence on his success in life; and
fortunately a love for the beautiful could not be pressed out of him. Kind,
all-embracing Nature took him in her arms, and whispered many things to
preserve him from becoming a mere animal. All day long he was hard at
work; but the blossoming tree was his friend, and the bright little mill-
stream chatted cozily, and smiled when the good grandmother gave it his
clothes to wash. The miller’s donkey, ambling along through sun-lighted
paths over the hills, was a picture to him. From his small garret window he
could see the mill-wheel scattering bright drops in the moonlight; and he
fell asleep to the gentle lullaby of ever-flowing water. Other education than
this he had not.