0% found this document useful (0 votes)
13 views83 pages

Front Line PHP Building Modern Applications With PHP 8 Brent Roose PDF Download

The document is about the book 'Front Line PHP: Building Modern Applications with PHP 8' by Brent Roose, which serves as a comprehensive guide to modern PHP practices and features. It covers the evolution of PHP, including significant changes in versions 7 and 8, and provides insights into building maintainable and performant applications. The book is designed for both beginners and experienced developers, offering a unified narrative on PHP development and its ecosystem.

Uploaded by

kalelanawaaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views83 pages

Front Line PHP Building Modern Applications With PHP 8 Brent Roose PDF Download

The document is about the book 'Front Line PHP: Building Modern Applications with PHP 8' by Brent Roose, which serves as a comprehensive guide to modern PHP practices and features. It covers the evolution of PHP, including significant changes in versions 7 and 8, and provides insights into building maintainable and performant applications. The book is designed for both beginners and experienced developers, offering a unified narrative on PHP development and its ecosystem.

Uploaded by

kalelanawaaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Front Line Php Building Modern Applications With

Php 8 Brent Roose download

https://ebookbell.com/product/front-line-php-building-modern-
applications-with-php-8-brent-roose-34116456

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Front Line Of Freedom Keith P Griffler

https://ebookbell.com/product/front-line-of-freedom-keith-p-
griffler-23457206

Frontline Librarianship Life On The Job For Todays Librarians Guy


Robertson

https://ebookbell.com/product/frontline-librarianship-life-on-the-job-
for-todays-librarians-guy-robertson-23900026

Front Line Surgery A Practical Approach 1st Edition Ian Wedmore Auth

https://ebookbell.com/product/front-line-surgery-a-practical-
approach-1st-edition-ian-wedmore-auth-4388124

Front Line Extremity And Orthopaedic Surgery A Practical Guide 1st


Edition Lawrence B Bone

https://ebookbell.com/product/front-line-extremity-and-orthopaedic-
surgery-a-practical-guide-1st-edition-lawrence-b-bone-4697534
Front Line Public Diplomacy How Us Embassies Communicate With Foreign
Publics William A Rugh

https://ebookbell.com/product/front-line-public-diplomacy-how-us-
embassies-communicate-with-foreign-publics-william-a-rugh-5126500

Front Line Public Diplomacy How Us Embassies Communicate With Foreign


Publics William A Rugh Auth

https://ebookbell.com/product/front-line-public-diplomacy-how-us-
embassies-communicate-with-foreign-publics-william-a-rugh-auth-5380894

Front Line Surgery A Practical Approach 2nd Edition Matthew J Martin

https://ebookbell.com/product/front-line-surgery-a-practical-
approach-2nd-edition-matthew-j-martin-6616660

Frontline Leadership How To Eliminate Complacency And Build Allin


Engagement 1st Edition Patrick Nelson

https://ebookbell.com/product/frontline-leadership-how-to-eliminate-
complacency-and-build-allin-engagement-1st-edition-patrick-
nelson-62320944

Front Line Nurse Rosie James

https://ebookbell.com/product/front-line-nurse-rosie-james-48417790
Front Line PHP
Building modern applications
with PHP 8

Brent Roose
Front Line PHP
Building modern applications
with PHP 8

Brent Roose
Published 2020 by Spatie.

Reviewers: Freek Van der Herten, Matthias Noback, Stephen Moon, Wouter Brouwers
Design & composition: Sebastian De Deyne, Willem Van Bockstal

This book is a distillation of the lessons learned by the Spatie team the past three years:
Adriaan, Alex, Brent, Jef, Freek, Niels, Rias, Ruben, Sebastian, Willem, and Wouter.

Version 5bc80b1-4
To report errors, please send a note to [email protected].

Created in Belgium
Table of Contents
Foreword........................................................................................................................... 7
Preface.............................................................................................................................. 9
PART I: PHP, the Language............................................................................................ 10
01. PHP Today 11
02. New Versions 13
03. PHP's Type System 25
04. Static Analysis 43
05. Property Promotion 53
06. Named Arguments 65
07. Attributes 77
08. Short Closures 95
09. Working with Arrays 99
10. Match 107
PART II: Building With PHP........................................................................................... 114
11. Object Oriented PHP 115
12. MVC Frameworks 137
13. Dependency Injection 155
14. Collections 167
15. Testing 171
16. Style Guide 179
PART III: PHP In Depth.................................................................................................. 190
17. The JIT 191
18. Preloading 201
19. FFI 215
20. Internals 219
21. Type Variance 225
22. Async PHP 231
23. Event Driven Development 235
In Closing......................................................................................................................247
Foreword

By Roman Pronskiy

PHP has changed the world. More than 5 million developers are now using this lan-
guage worldwide to create a variety of applications. But the world is changing PHP as
well. Rasmus Lerdorf, the creator of the language, once noted that "a good solution
should steal/borrow existing technology". And this is true. PHP takes the best ideas
from other ecosystems and improves on them.

It's been 5 years since the release of PHP 7.0. In this time, as the community has
matured and needed new features, the language team has been listening to the com-
munity and implementing the features. This is what has led PHP to introduce stricter
typing, more concise syntax, static analyzers, etc.

“It is not the strongest of the species that survives, nor the most intelligent that sur-
vives. It is the one that is most adaptable to change.” - Leon C. Megginson’s interpre-
tation of Darwin’s ideas is an insight that guides PHP year after year.

I was still in school when I first saw PHP, and at the time I had no idea that I would go
on to work with it professionally. Back then, in 2004, the main problem the internet
had was searching for information. Today, because so much information is readily
available, the problem is not searching information but filtering and identifying what is
useful. It is, to lean on an old cliché, like looking for a $needle in a $haystack – or was
it the other way around? Anyway, how do we dig up the really valuable things in these
endless feeds mixed with ads and notifications?
8

It's impossible to give a comprehensive answer for all areas, but for PHP the answer is
here – Front Line PHP.

This book gives a core of knowledge about everything that concerns the PHP’s devel-
opment today and in the near future. This is not a paraphrase of documentation, but
rather a thoughtful and meaningful development experience in short and clear for-
mulations. It offers a fresh look at the newest features of the language, as well as at
some that are already familiar.

Writing quality code in PHP has simultaneously become both easier and more com-
plicated. On the one hand, there are many new features and tools at a developer's
disposal. On the other hand, you need to juggle them elegantly in order to solve real
problems beautifully and easily.

That’s what this book is really about. Complex things in simple words. How to apply
them. Principles and practices. It is a fishing rod, in a sea full of fish.

There has never been a better time to work with PHP. And this book is one of the best
ways to learn it.

I hope you enjoy it!


9

Preface

When I started writing PHP, there were little resource available that could teach the
quality I expected to learn. Many online resource are either outdated or focussed on
absolute beginners. So about four years ago, I decided I wanted to contribute in a
qualitative way to the PHP community. I started a blog, which has grown quite popular
by now, and the writing never stopped.

The downside of a blog though is that each post is a small island on its own. You can't
expect visitors to have read all your previous posts. It's difficult to tell a story from
start to end, to have a continuous narrative on a blog.

Meanwhile I was fortunate to be able to work at a company that valued all I've written
before, and where each colleague is passionate about their work. Together we
decided to work on something that's more than individual posts or thoughts, some-
thing that tells the story of writing modern day PHP, something that would eventually
become this book.

This book is going to be a great stepping stone for all PHP developers; whether you're
a beginner or expert: you'll be able to learn lots. This book is a unified story, it con-
nects the dots that we've been working on for several years. This was my personal
goal when writing it, and I believe we've managed to do just that.

I wish you a great time reading, let's begin!


PART I

PHP, the Language


11

CHAPTER 01

PHP Today

I've been programming with PHP for 10 years now. During that time I've come to
really appreciate and enjoy the language. I realise not everyone would agree with that
sentiment: many consider PHP to be a broken and quirky language. Yet still, it runs
large portions of the web. So why do I enjoy writing it and why is it used so abundant-
ly? PHP's success, for over more than 25 years, isn't thanks to it being the perfect
language, but rather because it's an accessible one. PHP is easy to set up, run and
to write. Unfortunately, it's also easy to write terrible code, but still have a working
program. There are lots of online resources showing quick, easy and dirty ways to get
things done in PHP. Quick and easy, sure; but also insecure, unmaintainable and slow.

On top of that, it was a language where you seemingly almost always had to write
quirky code to get things working. That was certainly the case 10 years ago. However,
those days are gone, at least if you choose to embrace PHP's modern features. It has
seen a remarkable evolution over the past decade and has become a language I enjoy
everyday.

PHP isn't the same old crappy language remembered by many. Today, the language
is used to build high-profit, large-scale applications, and it does so just fine. With
PHP 7 and PHP 8 we received a significant improvement in the language syntax and
feature-set, as well as its performance. In addition, with frameworks like Laravel and
Symfony came versatile and flourishing communities.

PHP still isn't the perfect web-development language. Just like Ruby, Python, Java,
C# and JavaScript also aren't. Yet PHP programmers manage to achieve great results,
12 Front Line PHP

and enjoy writing code whilst doing so. Throughout this book we'll look at PHP as it is
today. We'll:

• explore what changed over the years,


• ponder on how the language will evolve in the future,
• discuss the ecosystem and community surrounding it, and
• show how PHP can be used to write modern-day, performant, and maintainable
code.

We'll also cover topics like:

• new syntax and language constructs,


• PHP's type system,
• what proper object oriented programming looks like in PHP,
• new core technologies like preloading, the JIT and FFI, and
• writing readable code.

Finally, we'll explore PHP's ecosystem:

• MVC and testing frameworks,


• async PHP, and
• tooling like static analysers.

You'll learn to love the modern language that is PHP.

Naturally we'll see lots of code in this book, so I figure it's important to understand
what that code exactly means. In the next few chapters we'll start from the ground up
and discuss everything new in PHP's recent evolution.
13

CHAPTER 02

New Versions

Since this book aims to bring you up to speed with modern PHP practices, it's im-
portant to know what happened to the language over the past decade or so. With the
development and release of PHP 7, the PHP landscape changed dramatically. I like to
think of the PHP 7.x versions as a maturity phase for the language, so this is where we
will start.

First and foremost, PHP 7.0 comes with a significant performance boost. Much of
PHP's core was rewritten, which resulted in a noticeable difference. It's not uncommon
to see your application run two or three times as fast, just by using PHP 7 or higher.
Thanks to one of PHP's core values — maintaining backwards compatibility — old PHP
5 codebases can easily be updated to benefit from these changes.

What happened to 6?

PHP 5.6 was the latest version in the 5 series, with the next one being 7.0. What
happened to version 6? The core team started working on it, only to realise
rather late that there were major issues with the internal implementation.
They decided to rework the engine once again, but "PHP 6" was already being
written. To avoid confusion, they decided to skip version 6, and jump straight to
PHP 7.

The story of PHP 6 has become folklore within the community. If you want to
know the in-depth story, you can do a quick Google search.
14 Front Line PHP

Even though PHP 7.0 was such a milestone, we've since moved on from it as well.
PHP 7.0 is already considered old: it was released in 2015 and didn't receive updates
anymore five years later. Around the late 5.x releases, PHP adopted a strict release
cycle: every year brings one new version. Most versions are actively supported for
two years, followed by one year of additional security support. After three years, you
should update, as the version you are using doesn't get security patches anymore.

Arguably, it's even better to follow along with the latest version. There will always
be minor breaking changes and deprecations, but most code can easily be updated.
There even are great automated tools that will take your existing codebase, detect
any upgrading errors, and fix them automatically.

Automation

One of those automated tools is called Rector which has grown in popularity
over the years: https://github.com/rectorphp/rector. Rector can update your
codebase automatically across several PHP versions and is a great tool to know
about if you ever have to deal with legacy projects.

In the next few chapters, we'll take a deep dive into the features added in PHP 7 and
PHP 8. Before doing that, we'll start by looking at the smaller yet significant changes
in this chapter.
Chapter 02 - New Versions15

Trailing commas

Support for trailing commas has been added incrementally up until PHP 8.0. They are
now supported in arrays, function calls, parameter lists, and closure use statements.

Trailing commas are a somewhat controversial topic among developers. Some people
like them; others hate them. One argument in favour of trailing commas is that they
make diffs easier. For example, imagine an array with two elements:

$array = [
$foo,
$bar
];

Next you'd need to add a third:

$array = [
$foo,
$bar,
$baz
];
16 Front Line PHP

Version control systems such as GIT would list two changes instead of one, because
you really did make two actual changes. If you'd always used trailing commas, you
wouldn't need to alter the existing lines:

$array = [
$foo,
$bar,
$baz,
];

Besides version control diffs, trailing commas can also be considered "easier" to
reason about because you never have to worry about adding an extra comma or not.
You might not prefer this writing style, and that's fine. We'll discuss the importance of
a style guide in a later chapter.

Formatting numeric values

You can use an underscore to format numeric values. This underscore is completely
ignored when the code is parsed but makes long numbers easier to read by humans.
Chapter 02 - New Versions17

This can be especially useful in tests. Take the following example: we're testing an
invoice flow and we need to pass in an amount of money. It's a good idea to store
money in cents, to prevent rounding errors, so using an _ makes it clearer:

public function test_create_invoice()


{
// $100 and 10 cents
$invoice = new Invoice(100_10);

// Assertions
}

Anonymous classes

Anonymous classes were added in PHP 7.0. They can be used to create objects on the
fly; they can even extend a base class. Here's an example in a test context:

public function test_dto_type_checking_with_arrays(): void


{
$dto = new class(
['arrayOfInts' => [1, 2]]
) extends DataTransferObject {
/** @var int[] */
public array $arrayOfInts;
};

// Assertions
}
18 Front Line PHP

Flexible heredoc

Heredoc can be a useful tool for larger strings, though they had an annoying indenta-
tion quirk in the past: you couldn't have any whitespaces in front of the closing delim-
iter. In effect, that meant you had to do this:

public function report(): void


{
$query = <<<SQL
SELECT *
FROM `table`
WHERE `column` = true;
SQL;

// …
}

Fortunately, you can now do this:

public function report(): void


{
$query = <<<SQL
SELECT *
FROM `table`
WHERE `column` = true;
SQL;

// …
}

The whitespace in front of the closing marker will be ignored on all lines.
Chapter 02 - New Versions19

Exception improvements

Let's take a look at two smaller additions in PHP 8. First: a throw statement is now
an expression. That means you can use it in more places, such as the null coalescing
righthand operand, or in short closures; we'll cover both of those features in-depth
later.

// Invalid before PHP 8


$name = $input['name'] ?? throw new NameNotFound();

// Valid as of PHP 8
$name = $input['name'] ?? throw new NameNotFound();

$error = fn (string $class) => throw new $class();

Second: exceptions support non-capturing catches. There might be cases where you
want to catch an exception to keep the program flow going and not do anything with
it. You always had to assign a variable to the caught exception, even when you didn't
use it. That's not necessary anymore:

try {
// Something goes wrong
} catch (Exception) {
// Just continue
}
20 Front Line PHP

Weak references and maps

PHP 7.4 added the concept of weak references. To understand what they are, you
need to know a little bit about garbage collection. Whenever an object is created, it
requires some memory to keep track of its state. If an object is created and assigned
to a variable, then that variable is a reference to the object. As soon as there are no
references to an object anymore, it cannot be used, and it doesn't make sense to keep
it in memory. That's why the garbage collector sometimes comes along looking for
those kinds of objects and removes them, freeing memory.

Weak references are references to objects which don't prevent them from being
garbage collected. This feature on its own might seem a little strange, but they allow
an interesting use case as of PHP 8, combined with weak maps: a map of objects
which are referenced using weak references.

Take the example of ORMs: they often implement caches which hold references to
entity classes to improve the performance of relations between entities. These entity
objects can not be garbage collected, as long as this cache has a reference to them,
even if the cache is the only thing referencing them.

If this caching layer uses weak references and maps instead, PHP will garbage collect
these objects when nothing else references them anymore. Especially in the case
of ORMs, which can manage several hundred, if not thousands of entities within a
request; weak maps can offer a better, more resource-friendly way of dealing with
these objects.
Chapter 02 - New Versions21

Here's what weak maps look like:

class EntityCache
{
public function __construct(
private WeakMap $cache
) {}

public function getSomethingWithCaching(object $object): object


{
if (! isset($this->cache[$object])) {
$this->cache[$object] = $this
->computeSomethingExpensive($object);
}

return $this->cache[$object];
}

// …
}

In this example, we cache the result of an expensive operation related to an object


in a cache. If the result doesn't exist yet, we'll compute it once. Thanks to weak
maps, this object can still be garbage collected if there are no other references to it
anymore.
22 Front Line PHP

The JIT

The JIT — just in time — compiler is a core mechanism added in PHP 8 which can
significantly speed up PHP code.

A JIT compiler will look at code while running and tries to find pieces of that code that
are executed often. The compiler will take those parts and compile them to machine
code — on the fly — and use the optimised machine code from then on out. The tech-
nique can be used in interpreted languages like JavaScript, and now also in PHP. It has
the potential to improve an application's performance significantly.

I say "potential" because there are a few caveats we must take into account. I'll keep
those and everything else JIT-related for the chapter dedicated to the JIT.

Class shorthand on objects

The ::class shorthand was added in PHP 5.5 to quickly get the full class name of an
imported one:

$className = Offer::class;

In PHP 8 this also works with variables:

$className = $offer::class;
Chapter 02 - New Versions23

Improved string to number comparisons

One of PHP's dynamic type system strengths is one of its weaknesses at the same
time: type juggling. PHP will try to change a variable's type when it encounters a
strange piece of code. Here's an example where strings and numbers are compared:

'1' == 1 // true

If you don't want this type juggling, you'd use the triple === sign instead:

'1' === 1 // false

There are strange edge cases when using weak comparisons, though. The following
returns true in versions before PHP 8:

'foo' == 1 // true

As of PHP 8, this behaviour is improved. The example above, as well as other edge
cases, would now return false correctly.

'foo' == 1 // false
24 Front Line PHP

Changes to the error control operator

One last notable change is that the @ operator no longer silences fatal errors. You can
still use it to silence other kinds of errors, like so:

$file = @file_get_contents('none/existing/path');

In cases where you don't use the @ operator, an error would be triggered, but with @,
$file will simply be false. If, on the other hand, a fatal error is thrown in PHP 8, the @
operator wouldn't ignore it anymore.

Deep down in the core

There are two low-level components added to PHP's core with the 7.4 update: FFI and
preloading. These are two complex topics on their own, each with their own chapter.
I'll briefly mention them here, though.

FFI — a.k.a. foreign function interface — allows PHP to speak to shared libraries
written in, for example C, directly. To put that in other words: it's possible to write PHP
extensions and ship them as composer packages without installing the low-level PHP
extensions themselves. I promise we'll dive deeper into this soon!

The other one — preloading — enables you to compile PHP code on server startup.
That code will be kept in memory for all subsequent requests. It can speed up your
average PHP web framework since it doesn't have to boot anymore on every request.
Again: this one deserves a chapter on its own.

So with these random little features out of the way, let's dig deeper into all great
things added to PHP over the past years!
25

CHAPTER 03

PHP's Type System

One of the most significant features of PHP 7, besides performance, is its improved
type system. Granted: it took until PHP 8 before most key features were implement-
ed, but overall, PHP's type system has improved significantly over the years. With
its maturing type system, some community projects started to use types to their full
extent. Static analysers were built, which opened the doors for a whole other way
of programming. We'll dig deeper into the benefits of those static analysers in the
next chapter. For now, we'll focus on what exactly changed within PHP's type system
between version 5 and 8.

First of all, more built-in types were added: so called "scalar" types. These types are
integers, strings, booleans and floats:

public function formatMoney(int $money): string


{
// …
}
26 Front Line PHP

Next (you might have noticed this in the previous example already) return types were
added. Before PHP 7 you were already able use types but only for input parameters.
This lead to a mix of doc block types and inline types — some might call it a mess:

/**
* @param \App\Offer $offer
* @param bool $sendMail
*
* @return \App\Offer
*/
public function createOffer(Offer $offer, $sendMail)
{
// …
}

Some developers who didn't want to deal with this kind of messy code chose not
to use types at all. After all, there was only a limited level of "type safety", since doc
blocks types aren't interpreted at all. Your IDE, on the other hand, would be able
to understand the doc block version, but for some people, this wasn't enough of a
benefit. As of PHP 7.0, however, the previous example could be rewritten like so:

public function createOffer(Offer $offer, bool $sendMail): Offer


{
// …
}

It's the same information, but much more concise and actually checked by the inter-
preter — we'll dive into the benefits of a type system and type safety later.
Chapter 03 - PHP's Type System27

Besides parameter and return types, there are now also typed properties for classes.
Just like parameter and return types, they are opt-in; PHP won't do any type checks.

class Offer
{
public string $offerNumber;

public Money $totalPrice;


}

You can see both scalar types and objects are allowed, just like with parameter and
return types.

Now, typed properties have an interesting feature to them. Take a look at the follow-
ing example and notice that despite what you might think at first sight, it is valid and
won't throw any errors:

class Money
{
public int $amount;
}

$money = new Money();

In this example, Money doesn't have a constructor, and no value is set in its $amount
property. Even though the value of $amount isn't an integer after constructing the
28 Front Line PHP

Money object, PHP will only throw an error when we're trying to access the property,
later in the code:

var_dump($money->amount);

// Fatal error: Typed property Money::$amount


// must not be accessed before initialization

As you can see in the error message, there's a new kind of variable state: uninitialized.
If $amount didn't have a type, its value would simply be null. Typed properties can be
nullable, so it's important to make a distinction between a type that was forgotten and
a type that's null. That's why "uninitialized" was added.

There are a few essential things to remember about uninitialized:

• As we just saw, you cannot read from uninitialized properties; doing so will result
in a fatal error.
• Because the uninitialized state is checked when accessing a property, you're
able to create an object with an uninitialized property.
• You're allowed to write to an uninitialized property before reading it, which
means you could do $money->amount = 1 after constructing it.
• Using unset on a typed property will make it uninitialized, while unsetting an
untyped property will make it null.
• While the uninitialized state is only checked when reading a property's value,
type validation is done when writing to it. This means that you can be sure no
invalid type will ever end up as a property's value.

I realise this behaviour might not be what you'd expect a programming language to
do. I've mentioned before that PHP tries very hard not to break backwards compat-
ibility with their updates, which sometimes results in compromises like the uninitial-
ized state. While I think that a variable's state should be checked immediately after
Chapter 03 - PHP's Type System29

constructing an object, we'll have to make do with what we have. At least it's another
good reason to make use of static analysis in the next chapter.

Dealing with null

While we're on the topic of uninitialized state, let's also discuss null. Some have
called the concept of null a "billion-dollar mistake", arguing it allows for a range of
edge cases that we have to consider when writing code. It might seem strange to
work in a programming language that doesn't support null, but there are useful pat-
terns to replace it, and get rid of its pitfalls.

Let's illustrate those downsides first with an example. Here we have a Date value
object with a timestamp variable, format function and static constructor called now.

class Date
{
public int $timestamp;

public static function now(): self { /* … */ }

public function format(): string { /* … */ }

// …
}
30 Front Line PHP

Next, we have an invoice with a payment date:

class Invoice
{
public ?Date $paymentDate = null;

// …
}

The payment date is nullable because invoices can be pending and not yet have a
payment date.

As a side note: take a look at the nullable notation; I've already mentioned it but
haven't shown it until now. We've prefixed Date with a question mark, indicating that
it can either be Date or null. We've also added a default = null value, ensuring the
value is never uninitialized to prevent all those runtime errors you might encounter.

Back to our example: what if we want to do something with our payment date's time-
stamp?

$invoice->paymentDate->timestamp;

Since we're not sure $invoice->paymentDate is a Date or null, we risk running into
runtime errors:

// Trying to get property 'timestamp' of non-object


Chapter 03 - PHP's Type System31

Before PHP 7.0, you'd use isset to prevent those kinds of errors:

isset($invoice->paymentDate)
? $invoice->paymentDate->timestamp
: null;

That's rather verbose, though, and is why a new operator was introduced: the null
coalescing operator.

$invoice->paymentDate->timestamp ?? null;

This operator will automatically perform an isset check on its left-hand operand. If
that returns false, it will return the fallback provided by its righthand operand. In this
case, the payment date's timestamp or null. It is a nice addition that reduces the com-
plexity of our code.

PHP 7.4 added another null coalescing shorthand: the null coalescing assignment
operator. This one not only supports the default value fallback, but will also write it
directly to the left-hand operand. It looks like this:

$temporaryPaymentDate = $invoice->paymentDate ??= Date::now();

So if the payment date is already set, we'll use that one in $temporaryPaymentDate,
otherwise we'll use Date::now() as the fallback for $temporaryPaymentDate and also
write it to $invoice->paymentDate immediately.
32 Front Line PHP

A more common use case for the null coalescing assignment operator is a memoiza-
tion function: a function that stores the result once it's calculated:

function match_pattern(string $input, string $pattern) {


static $cache = [];

return $cache[$input][$pattern] ??=


(function (string $input, string $pattern) {
preg_match($pattern, $input, $matches);

return $matches[0];
})($input, $pattern);
}
Chapter 03 - PHP's Type System33

This function will perform a regex match on a string with a pattern, but if the same
string and same pattern are provided, it will simply return the cached result. Before we
had the null coalescing operator assignment, we'd need to write it like so:

function match_pattern(string $input, string $pattern) {


static $cache = [];

$key = $input . $pattern;

if (! isset($cache[$key])) {
$cache[$key] = (function (string $input, string $pattern) {
preg_match($pattern, $input, $matches);

return $matches[0];
})($input, $pattern);
}

return $cache[$key];
}

There's one more null-oriented feature in PHP added in PHP 8: the nullsafe operator.
Take a look at this example:

$invoice->paymentDate->format();

What happens if our payment date is null? You'd again get an error:

// Call to a member function format() on null


34 Front Line PHP

Your first thought might be to use the null coalescing operator, but that wouldn't work:

$invoice->paymentDate->format('Y-m-d') ?? null;

The null coalescing operator doesn't work with method calls on null. So before PHP
8, you'd need to do this:

$paymentDate = $invoice->paymentDate;

$paymentDate ? $paymentDate->format('Y-m-d') : null;

Fortunately there's the nullsafe operator which will only perform method calls when
possible and otherwise return null instead:

$invoice->getPaymentDate()?->format('Y-m-d');

Dealing with null — there's another way

I started this section saying null is called a "billion-dollar mistake", but next, I showed
you three ways PHP is embracing null with fancy syntax. The reality is that null is a
frequent occurrence in PHP, and it's a good thing we have syntax to deal with it in a
sane way. However, it's also good to look at alternatives to using null altogether. One
such alternative is the null object pattern.
Chapter 03 - PHP's Type System35

Instead of one Invoice class that manages internal state about whether it's paid or
not; let's have two classes: PendingInvoice and PaidInvoice. The PendingInvoice
implementation looks like this:

class PendingInvoice implements Invoice


{
public function getPaymentDate(): UnknownDate
{
return new UnknownDate();
}
}

PaidInvoice looks like this:

class PaidInvoice implements Invoice


{
// …

public function getPaymentDate(): Date


{
return $this->date;
}
}

Next, there's an Invoice interface:

interface Invoice
{
public function getPaymentDate(): Date;
}
36 Front Line PHP

Finally, here are the two date classes:

class Date
{
// …
}

class UnknownDate extends Date


{
public function format(): string
{
return '/';
}
}

The null object pattern aims to replace null with actual objects, objects that behave
differently because they represent the "absence" of the real object. Another benefit
of using this pattern is that classes become more representative of the real world:
instead of a "date or null", it's a "date or unknown date", instead of an "invoice with a
state" it's a "paid invoice or pending invoice". You wouldn't need to worry about null
anymore.

$invoice->getPaymentDate()->format(); // A date or '/'

You might not like this pattern, but it's important to know that the problem can be
solved this way.
Chapter 03 - PHP's Type System37

Changing types

Something happened in the above code samples that I wrote down as a fact, yet it's a
significant addition to PHP's type system. We were able to change method signatures
during inheritance. Take a look at the Invoice interface:

interface Invoice
{
public function getPaymentDate(): Date;
}

It declares the return type of getPaymentDate as Date, yet we changed it in our


PendingInvoice to UnknownDate:

class PendingInvoice implements Invoice


{
public function getPaymentDate(): UnknownDate
{
/* … */
}
}

This powerful technique is called type variance; it's supported as of PHP 7.4. It's so
powerful (and a little complex) that we'll spend a whole chapter on the topic later
in this book. For now, all you need to know is that return types and input parameter
types are allowed to change during inheritance, but both have different rules to follow.

Another interesting detail has to do with nullable types. There's a difference between
a nullable type using ? and a default = null value; you've seen them used together
already in a previous example. The difference is this: if you make a type nullable in
38 Front Line PHP

PHP, you're still expected to pass something to that function; you can't just skip the
parameter:

function createOrUpdate(?Offer $offer): void


{
// …
}

createOrUpdate();

// Uncaught ArgumentCountError:
// Too few arguments to function createOrUpdate(),
// 0 passed and exactly 1 expected

So by adding an explicit = null default value, you're allowed to omit the value alto-
gether:

function createOrUpdate(?Offer $offer = null): void


{
// …
}

createOrUpdate();
Chapter 03 - PHP's Type System39

Unfortunately, because of backwards compatibility, there's a little quirk with this


system. If you assign a default = null value to a variable, it'll always be nullable. Re-
gardless of whether the type is explicitly made nullable or not, so this will be allowed:

function createOrUpdate(Offer $offer = null): void


{
// …
}

createOrUpdate(null);

Union and Other Types

There are still a few more things worth mentioning in this chapter, and the most excit-
ing one is union types. They allow you to type hint a variable with several types. Note:
the input needs to be one of those declared types. Here's an example:

interface Repository
{
public function find(int|string $id);
}

Be careful not to overuse union types, though. Too many types in the same union can
indicate that this function is trying to do too much at once.

For example: a framework might allow you to return both a Response and View object
from controller methods. Sometimes it's convenient to directly return a View, while
other times you want to have fine-grained control over the response. These are cases
where a union type on Response|View is fine. On the other hand, if you have a function
40 Front Line PHP

that accepts a union of array|Collection|string, it's probably an indication that the


function has to do too many things. It's best to think about finding a common ground
in those cases; maybe only accept Collection or array.

Finally, there are three more built-in types available.

There's the static return type available in PHP 8. It indicates that a function returns
the class where that function was called from. It differs from self since that one
always refers to the parent class, while static can also indicate the child class:

abstract class Parent


{
public static function make(): static { /* … */ }
}

class Child extends Parent { /* … */ }

$child = Child::make();

In this example, static analysis tools and IDEs now know that $child is an instance
of Child. If self was used as a return type, they would think it was an instance of
Parent. Also note that the static keyword and static return type are two different
concepts; they just happen to have the same name (which is the case in many other
languages).

There's also the void return type added in PHP 7.1. It checks whether nothing is re-
turned from a function. Note that void cannot be combined into a union.

Finally, there's the mixed type, also available as of PHP 8. mixed


can be used to type hint "anything". It's a shorthand for the union of
array|bool|callable|int|float|null|object|resource|string. Think of mixed as
the opposite of void.
Chapter 03 - PHP's Type System 41

Generics and Enums

There are still two major features missing in PHP's type system today: generics and
enums. I wish I could write about them in this book, but unfortunately, they aren't sup-
ported by the language yet.

There have been efforts in the past to add both features, but there hasn't been any
consensus about how enums should be implemented, and generics would have too
large an impact on runtime performance.

This raises an interesting question: why do we need to check types at runtime? Isn't
that too late? If something goes wrong, the program crashes anyway. That's exactly
the topic we'll look at in-depth in the next chapter.
42 Front Line PHP
 43

CHAPTER 04

Static Analysis

Having spent a whole chapter on PHP's type system, I realise I haven't discussed
why you want to use it. I realise a significant part of the community doesn't like using
PHP's type system, so it's important to discuss both the pros and cons thoroughly.
That's what we'll do in this chapter. We'll start by discussing the value provided by a
type system.

Many think of programming languages with a stricter type system to have fewer or no
runtime errors. There's the popular saying that a strong type system prevents bugs,
but that's not entirely true. You can easily write bugs in a strongly typed language, but
a range of bugs is not possible anymore since a good type system prevents them.

Are you unsure what the difference is between strong, weak, static and dynamic
type systems? We'll cover the topic in-depth later in this chapter!

Imagine a simple function: rgbToHex. It takes three arguments, each of which are in-
tegers between 0 and 255. The function then converts the integers to a hexadecimal
string. Here's what this function's definition might look like without using types:

function rgbToHex($red, $green, $blue) {


// …
}
44 Front Line PHP

Since we want to ensure our implementation of this function is correct, we write tests:

assert(rgbToHex(0, 0, 0) === '000000');

assert(rgbToHex(255, 255, 255) === 'ffffff');

assert(rgbToHex(238, 66, 244) === 'ee42f4');

These tests ensure that everything works as expected. Right?

Well… we're only testing three out of the 16,777,216 possible RGB combinations. But
logic reasoning tells us that if these three sample cases work, we're probably safe.
What happens though if we pass floats instead of integers?

rgbToHex(1.5, 20.2, 100.1);

Or numbers outside of the allowed range?

rgbToHex(-504, 305, -59);

What about null?

rgbToHex(null, null, null);

Or strings?

rgbToHex('red', 'green', 'blue');


Chapter 04 - Static Analysis 45

Or the wrong number of arguments?

rgbToHex();
rgbToHex(1, 2);
rgbToHex(1, 2, 3, 4);

Or a combination of the above?

I can easily think of five edge-cases we need to test before there's relative certain-
ty that our program does what it needs to do. That's at least eight tests we need to
write, and I'm sure you can come up with a few others. These are the kinds of prob-
lems a type system aims to partially solve, and note the word partially because we'll
come back to it. If we filter the input by a specific type, many of our tests become
obsolete. Say we'd only allow integers:

function rgbToHex(int $red, int $green, int $blue)


{
// …
}

You can think of types as a subcategory of all available input; it's a filter that only
allows specific items.

Let's take a look at the tests that aren't necessary anymore thanks to our int type
hint:

• Whether the input is numeric


• Whether the input is a whole number
• Whether the input isn't null
46 Front Line PHP

We still need to check whether the input number is between 0 and 255. At this point,
we run against the limitations of many type systems, including PHP's. Sure we can use
int, though in many cases, the category described by this type is still too large for
our business logic: int would also allow -100 to be passed, which wouldn't make any
sense for our function. Some languages have a uint or "unsigned integer" type; yet it
is also too large a subset of "numeric data".

Luckily, there are ways to address this issue.

One approach could be to use "configurable" or generic types, for example


int<min, max>. The concept of generics is known in many programming languages,
though unfortunately not in PHP. In theory, a type could be preconfigured so that it is
smart enough to know about all your business logic.
Chapter 04 - Static Analysis 47

Languages like PHP lack the flexibility of generic types, but we do have classes, which
can be used as types themselves. We could, for example, represent a configurable
"integer" with a class IntWithinRange:

class IntWithinRange
{
private int $value;

public function __construct(int $min, int $max, int $value)


{
if ($value <= $min || $value >= $max) {
throw new InvalidArgumentException('…');
}

$this->value = $value;
}

// …
}

So whenever we're using an instance of IntWithinRange, we can ensure its value


is constrained within a subset of integers. But this only works when constructing
IntWithinRange. In practice, we can't ensure its minimum and maximum value in our
rgbToHex function, meaning we can't say we only accept IntWithinRange object with
48 Front Line PHP

a minimum of 0 and a maximum of 255. Therefore we can only say we accept any
object with the type of IntWithinRange:

function rgbToHex(
IntWithinRange $red,
IntWithinRange $green,
IntWithinRange $blue
) {
// …
}

To solve this, we need an even more specific type: RgbValue:

class RgbValue extends IntWithinRange


{
public function __construct(int $value)
{
parent::__construct(0, 255, $value);
}
}

We've arrived at a working solution. By using RgbValue, most of our tests become re-
dundant. We now only need one test to test the business logic: "given three RGB-valid
colors, does this function return the correct HEX value?" — a great improvement!

function rgbToHex(RgbValue $red, RgbValue $green, RgbValue $blue)


{
// …
}
Discovering Diverse Content Through
Random Scribd Documents
“And last night you ran away to bed without even a good-night!”
with upbraiding in his voice.

“Oh, did you miss me? I never supposed you would. I was tired
sitting there, thinking my own thoughts.”

“Now we have plenty of time; tell them to me,” and his persuasive
tone penetrated her inmost being. What foolish things could she
repeat? Her face was scarlet.

“You know now I love you. I have told you so in words. I have told it
in many other ways. I confessed it to M. Denys before I went away
and he bade me wait patiently. For two years I have carried you in
my heart, yes, longer than that. You had your fling about other
women; no one has ever moved me. Every night I said, ‘One more
day has gone, and at the last I shall go back to the little girl in old
St. Louis that I carried in my arms all one night when she was worn
out with fatigue and hunger and cold. Renée——”

“I cannot leave Uncle Denys. I have said hundreds of times I never


would,” and her voice was sweet with pathos that penetrated his
inmost soul.

“But you need not. We have planned that. I will be a son to him in
all his declining years. No, you need never be separated.”

“Then you will stay!” exultingly. If she could once conquer she would
be generous and consent afterward. Did not love yield everything?

“I must go. We three will go.” His breath came in a gasp, his eyes
deepened with fervor, he caught both her hands; he could have
clasped her in his arms in a transport of rapture. Only—she stood up
so straight and resolute.

“So you have planned all this!” she cried in a passion that had a
pang for her as well as him. “And I am not anywhere. It makes no
difference what I want. I am like any bale of merchandise tossed
from one to the other. That is all a woman is worth! But you will find
I am not to be bandied about.”

She had lashed her emotion into tears, and pulled away her hands
with an impatient gesture.

“Heaven above knows what you are worth to both of us. No one will
ever love you more truly, more devotedly.”

Renée de Longueville fled swiftly away.


CHAPTER XX—WHEN A WOMAN WILL

“What ails the child?” inquired Mère Lunde. “She has not been like
herself the last fortnight. And now she is in there, crying as if her
heart would break. It is all that André Valbonais, I know. Why does
he not marry her and be done with it?”

“But if she will not?” Gaspard Denys shrugged his shoulders and
drew his brow into a frown.

“In my time a man knew how to make a woman say yes. And a
woman knew when she was going to get a good husband, which is
of the Lord. Gaspard Denys, you have spoiled her!”

Yes, he had spoiled her. A man did not know how to bring up a girl.
But she was so sweet in all her wilfulness, so loving in spite of little
tempers and authoritative ways, so dear to him, that if she had
wanted to walk over his body with her dainty feet he could hardly
have refused her. He went into her room and took her in his arms.

“You are too good to me!” she cried presently. “And I am a


miserable, hateful, quarrelsome, selfish little thing, wanting my own
way and then not happy or satisfied with it. Oh, how will you endure
me years and years, getting queerer as I grow old! For now we will
have to live here together always. I have sent André away. Oh, will
you care?”

There was no use arguing. She had cried herself into an


unreasonable passion. She had had her way. How much of it was
regret? None of it was satisfaction.
“Well, dear, then we must get along,” and his tone had a
tranquillizing cheerfulness in it. “There is no one I would like as well
for a son——”

“But you do not want to go to that wretched New Orleans?” in a


tone of incredulity.

She raised her head from his shoulder. Her swollen eyes and tear-
stained face melted his heart.

“You know we were going some time. It is well worth seeing. But we
do not need to take André.”

“Yet you like him so,” with her old waywardness.

“Yes. And I am sorry you do not.”

She hid her face again. She did like him. She felt it in the hot color
that stained her cheek.

“He will be gone a year—that is not long,” she said in a rather


hopeful tone.

“Or, he might decide to stay longer. If he has nothing to call him


back——”

They would be lonely without him. She would be lonely. After all,
there were few young men to compare with him. And some time—if
he was quite sure she did not care for him, he might marry. She
never could marry any one else, but, then—men were different. Oh,
here was one who had never put a woman in his first love’s place!
And André was all alone in the world. Yes, he would need a wife——

“Oh, Uncle Gaspard, I am not worth all this love!” she cried
remorsefully.
“You will always be worth it to two men,” he said in so gentle a tone
that it pierced her heart. “I am much older than you, dear, and some
day I shall be called upon to take the journey from which one never
returns. Then you will be left quite alone.”

What made her think of the little girl in the old château to whom the
days were so long and lonesome? Yet, it would be very sad to be left
alone. And—after all——

There are so many “after alls” in life. And so many things seem
insurmountable when looked at in a moment of passion. Uncle
Denys could never give her wholly away, had never planned to do
that. Fathers and mothers were happy to have their children
married, and here she would not do this for the best friend she had,
nor for the man who loved her sincerely—that she loved—a little.

“You ought to shut me up in the loft and keep me on—on pemican,


which you know I hate, and declare you would never let me out until
—until——”

“A woman’s love must always be a free gift, Renée, darling. And if


you do not love André it would be sinning against him to marry him.”

She knew down deep in her heart that she did love him, that she
had waited these two years because there was no one like him to
her. Of course, she had not really meant that he should throw up his
fine prospects, but be willing to for her sake. And she knew now it
was all very foolish and wicked, and that she deserved to be left
alone for years and years and have them all full of sorrowful regret.

“I am going to turn over a new leaf, indeed I am,” and she slipped
out of Uncle Gaspard’s arms. “See what a fright I have made of
myself with red eyes and swollen face, and my hair frousled. Dinner
must be nearly ready. Oh, what a long morning! And I have made
you unhappy, when I love you so much,” in accents of tenderest
regret.
He kissed her and went away.

They were very silent at dinner. Mère Lunde grumbled because they
ate so little. Then Uncle Gaspard went out. The boats were loading
up with lead, as well as other materials, and he was interested in
that, and needed as well.

No one came during the evening. She heard the violins and singing
up the street, the fiddles and dancing down below. The fire was all
out; no one wanted it after the cooking was done. There were some
black charred ends and piles of ashes. It had a melancholy
appearance. And then she fancied herself as old as Mère Lunde,
sitting by the chimney corner, only Mère Lunde had married the man
of her choice—it seemed now to Renée that every one must have
done so—and though her two sons were dead, she had had them
once; and everybody must die some time. But to die without having
been very happy, that made her shudder. And, then, to know that
one had cast it away rather than give up a whim of will.

So the next day passed and the next. Sunday she and Uncle Gaspard
went to church. There would only be one Sunday more for André—
ten days. For her—how many?

Coming down the path they glanced at each other. What wonderful
languages live in the depths of the eyes! André came to her side,
and then she colored and the hand he took trembled, but she did
not withdraw it. They walked on homeward. She never knew
whether any one spoke or not. Uncle Gaspard was lingering behind,
giving thanks that he was likely to get his heart’s desire.

They paused at the garden gate. He opened it for her to pass. There
was midsummer richness and bloom in it, the homely every-day
herbs giving out a sweetness in their plain flowering that was
reviving. He followed her, but she made a little pause at the vine-
clad arbor.
“I am wilful and delight in my own way,” she began, and the words
trembled on the fragrant air. “I am like a briar that pricks you when
you would gather the rose——”

“But the rose is sweet for all that. And—I will take the rose.”

Then he kissed her throbbing red lips, her fluttering eyelids, just as
he had dreamed of doing many a time. And the bliss was sweeter
than any dream.

There was not much time to waste. Mère Lunde protested at first at
being left alone, but there would be Chloe, and the Marchands to
look after her, and neighbors were kindly.

Not much fuss was made in those days over wedding trousseaus.
Often one dress went through families, was even borrowed. But
Renée had no need of that.

So they went to church on Sunday and heard the banns called, and
every one nodded to his next neighbor with the confident air of
having known it all along. The next day Gaspard Denys gave his
darling away, and the priest joined their hands and blessed them.
Madame Chouteau gave them the wedding feast, which was a mid-
day dinner in the grand old house, much the finest residence in St.
Louis. It had not the boisterousness of most weddings, for only the
better part of the community were invited. Madame Chouteau could
do that.

They drank the bride’s health and gave her all good wishes. The
men considered André very lucky and he thought himself so, but
Renée’s fortune scarcely counted, since he would make one for
himself. Everything seemed sweet and solemn to Renée, and she
was awed in a sacred sort of way as this new life unfolded before
her.

They walked in quite a procession afterward. Gaspard Denys had


Madame Gardepier. They talked a little about the bridegroom, then
she said:

“Monsieur Denys, you have done a faithful duty toward the child.
You will miss her much. One can never be quite the same again. Is it
true you are going to New Orleans also?”

“Yes, madame. I have not been there for years.”

She had hoped it was not so. If he were lonely, he might turn to
others for consolation. And if the child went out of his life——

“But will her husband agree to share her love? Husbands are jealous
sometimes,” she commented rather gayly.

“He is like a son to me, and he knows it. You see, I am old enough
to be his father also.”

“Ah, M’sieu Denys, you should have had children of your very own,
and a woman to love in your home. You have such a noble and
tender heart you could have made some one so happy.”

Her heart beat as she said it. Why could he not be roused to the
hope even now?

“I think you know that I loved the child’s mother, and that we were
unfairly separated. If she had lived—but she died. And when I heard
the little one was sent across the sea by her father, who had small
regard for her, it was as if her mother, leaning over the wall of
heaven, called to me, and I did what I knew would set her heart at
rest.”

“But she had heaven and all the saints. And in that land of the blest
one cannot long for human loves. It is to those left on earth to
whom they are precious,” she returned, with a little longing in her
tone. She had been waiting for Renée’s marriage to take her out of
his life. Why should the child have so much?
“I think they know, those blessed ones. Ah, madame, if you had
been dying, instead of your husband, and leaving the little one,
would you not have pleaded with the very angels that some one
might be raised up to care for her? And if that had been one to
whom she would be doubly dear! So the child in one sense has been
like my own.”

And always her rival, Barbe Gardepier felt. Her last hope seemed to
drop as one lets fall a withered flower that has been sweet and is
still freighted with some dear remembrances.

They paused at her sister’s house.

“You will come in and say good-by to-morrow?”

“Yes,” and he bowed.

Why should things go so wrong in the world? Renée Freneau


defrauded of a lifelong happiness, of life itself, and she who had
seen such a blissful possibility twice in her short life shut out from
what would have been her brightest happiness.

He went his way thoughtfully. He had been so long used to a man’s


liberty that he did not care to enchain himself with matrimony. And
surely he would give Renée no rival to her children.

It was a gorgeous day and the fleet of boats glided out with music
and many a “Bon voyage!” The little girl had vanished, but Renée
remembered the first night she came, when in the bend of the river
they passed the old ruined heap, and the old French post-house
going to decay. Was it in some other life? She still had Uncle Denys,
and she was glad. What a wonderful thing it was to love a woman’s
memory all these years!

It was a pleasant journey, with only a few storms, one severe


enough to make them run into an inlet to get out of the fierce sweep
of the river. There was Cahokia, whose ruins were still visible.
Kaskaskia, despoiled of much of its valuable front, the town high
now above the river. Strange and curious sights to one who had
been no farther than St. Charles.

How would St. Louis look when they went back to it? Renée
wondered. For this to her was a marvellous city, more brilliant than
any dream ever made it. It seemed as if the whole world must have
been gathered in it when one heard the confusion of tongues.

They did not return the next summer, for still the business could not
spare André. But Monsieur Chouteau came down, and there were
journeys about to places of such bloom and beauty and mystery that
one almost had to hold one’s breath.

Strange things, too, were happening in the world beyond the great
river that seemed all to them. The colonies were growing more
stable, being welded together by chains of interest and pride and
patriotism into a grand country, but the Mississippi River would
always be its boundary. It could not pass that, men thought.

Over seas there were tumults and wars, and France in the throes of
a most fearful revolution. They heard a great deal about it here.
How hundreds of the nobility were thrown in prison, the King and
Queen executed and the mob quarrelling with its leaders.

Renée thought of the two little brothers in Paris that she had seen
on the day of her journey. And the Count. He was among the
nobility, and he was her father. She shuddered over the horrible
doings. And here was her other father, bright and happy and always
considering what would be for her pleasure.

Sometimes they read an unspoken wish in each other’s eyes.

“It is not quite St. Louis,” she would say, with a half smile meant to
be gay, but was pensive instead.
“No. But we will return presently,” the eyes full of cheerful light and
the tone hopeful.

“And never leave it again?”

“I am glad you cannot forget it.”

“Oh, there is no place like the home and the friends of childhood—
the larger childhood, when everything is impressed on one’s heart.
The old house and the shop and the wide chimneys and Mère
Lunde, and the Marchands with their babies. I know what it is to be
an exile.”

Still she and André were very happy, taking the leisure of life like
two children, growing into each other’s souls, laughing over some of
the old times. And she would say:

“How could you love me so well when I was horrid and provoking
and tormented you so?”

“But you had moments of rare sweetness, ma’m’selle; and


sometimes the bee works a long while before he can extract the
honey.”

“And you have never once been sorry?”

“The sorrow would have come if I had not gained you—a lifelong
sorrow.”

“And I like your strength, your determination, your resolution, André.


Oh, I like you altogether. I would not have one thought or line of you
changed.”

“You yielded so sweetly, ma’m’selle. It is the rose without the thorns.


And such tenderness! Ah, I do not wonder Father Gaspard gave up
all other women for love of you!” kissing the crown of her head, a
trick he had learned from Denys.
“Not altogether for me,” smiling with the distant look in her eyes, as
if she saw a heavenly vision. “For my mother as well. I wish I could
remember her better, but I was so small. And do you know, André, I
used to act like a fiend sometimes, I was so afraid he would love
Barbe. And now and then a great wave of sorrow sweeps over me,
thinking of all she has missed.”

“Madame Gardepier is a lovely woman. Still she does not look like
those who have had their heart’s longing satisfied. There is
something still needed.”

“And I could not even yet give up Papa Gaspard. I am still selfish.
Are you jealous, André?” raising beauful, beseeching eyes to him.

“He gave you to me long before you gave yourself—the treasure of


his life. I lost my father so young that I cannot tell what such a love
would have been like, but I know it could not be any tenderer. One
sees it in his eyes and the comfort he takes, the immeasurable
content. But he is longing for home. Dear, we will never leave St.
Louis again.”

They often made love to each other, she with a freedom that
wifehood had given her which was enchanting. Gaspard Denys took
deep satisfaction in his two children. There was one more dream,
but that was for some after-day fruition.

There was a much greater spirit of energy in this queer, half-


submerged town, with its muddy streets that sometimes were
positive streams. The ambition of the outside world was stirring
them, the interest that varied commerce brings. There were new
boats being builded for the old firm, and in one of these Renée went
up the river again to her old home.

There had been no great freshet since the one that had wrought
such destruction, but the swift current of spring had torn away some
of the old obstructions. Noble bluffs had settled to sunken ridges,
banks had slipped into the river and formed other high places full of
greenery and wild bloom. Caves of rocks swept out and left high in
some other place. It was wild and curious with a peculiar beauty. Its
partly ruined towns were recovering. There were little hamlets set so
near the river’s edge one wondered people had the courage to plant
them there. And there was all the Illinois side, the new country
showing already the energy of the new race combined of many
peoples.

Renée might have left St. Louis yesterday, so little had it changed in
the two years. The levee was in a better condition, some new docks
had been built. And, as usual, there was the throng to see the boats
come in, pouring down from the Rue de la Tour and the Rue de la
Place into the Rue Royale. Yet it was like an everyday sight at New
Orleans. Only the welcomes gave it a rapture she had never known
before. Madame Marchand had her arms about her. Other old friends
of girlhood, wives and mothers now, voices so confused, yet so glad,
that it was music to listen to them.

It was old St. Louis, but the little girl had gone forever. Madame
Valbonais, prettier than ever and with a style that was foreign to the
small town. Monsieur, grown a little stouter, fine and strong, yet
smiling with a face of gladness. Gaspard Denys, keeping close watch
over the mulatto nurse in gay coif and bright gown, who had in her
arms the little son of madame.

A triumphal procession escorted her home. How curiously dry the


streets were, and almost prim after the southern irregularity; the
riotous tangle of vines, the balconies full of ladies with fans, chatting
and waving to the passers-by, throwing coquettish smiles. The old
French air that had grown settled in fifty years, the queer houses,
and oh, yes, here was the garden, and Mère Lunde watching at the
gate, more bent than ever, crying tears of joy, and in her broken
voice repeating, “Oh, my little one! Oh, my little one!”

Yet it was strange, too, after all that luxuriance of growth and bloom
and fragrance, queer, crooked, busy streets, gay wine shops with
open doors and tables of men within playing cards or fiddling or
singing songs. Birds of every color and richest plumage filling the air
with melody, iridescent lizards creeping about winking with their
bright black eyes, alligators sunning themselves in the ooze, snakes
gliding about unmolested, throngs of almost naked children shining
in their blackness, ready to sing and dance, turn a dozen
somersaults or walk upside down for a copper—the vivid panorama
still floated before her eyes and gave her queer, mixed impressions.

Most of the people seemed to have stood still. Two or three very old
ones had died and several babies, but others had come to replace
them. Not a new house had been built; the stockade was getting
dilapidated. The Government House had been painted afresh, but
the old court-house was dingy enough. The priest’s house had been
repaired, the little garden was lovely with roses that were always
blooming, and the Chouteau grounds were like a beautiful park, so
well kept and thrifty.

“Oh,” André said, “I wonder if you will be sick with longing for all the
gayety and loveliness we have left behind?”

“Why, then, we can go there again,” she answered merrily, with


bright, contented eyes and a winsome smile. “It is so restful here.
And Papa Gaspard is so happy.”

He was hale and hearty and had not turned the half-century yet.
Then he was full of plans. They would move the shop down on the
Rue Royale and build a new room on to the old house. He had
brought home some ideas of improvement and comfort, of larger
living. It was not likely St. Louis would always stand still.

Madame Marchand was delighted to get her friend back again. There
was a new little girl, but Renée kept her beauty and winsomeness.
Wawataysee was still lithe and slim—it belonged to her tribe—and M.
Marchand was as devoted as ever. Oh, what days of talk it took to
make up all the past!
And Madame Gardepier had married and gone over to the Illinois
side to live on a big plantation. Pierre Menard had a mill for sawing
boards and a brewery for beer, no end of slaves and servants, full
fifty years of age, and two grown sons married. He coveted the little
Angelique Gardepier and sued hard for the mother, who would have
a luxurious life.

“But thou wilt be an American truly,” sighed Madame Renaud.

There was still a great prejudice against the Illinois people. Their
religion, or, rather, lack of religion, was a great stumbling-block.
Then their roaming lives, their apparent disregard of home ties, that
were so strong with the French.

But monsieur adored her in a very complimentary fashion, and she


was fain to satisfy her heart with it. Sometimes when the red-gold
splendors were fading from the sky, leaving the bluffs and pearl-gray
spaces on the opposite side like long avenues where the light shone
through, Barbe Menard would glance over and wonder what
particular merit there was in Renée de Longueville that the good
God should have given so much to her.
CHAPTER XXI—FROM ACROSS THE SEA

In the second year after Renée’s return two signal events happened.
A new little boy was born. She had coveted a girl for Papa Gaspard
to love as he had loved her, but one had to be content with what
God sent, and the boy was bright and strong.

“No,” Papa Gaspard said when they were talking it over one day,
“there will be plenty of time for girls. I am not sorry. But I shall ask a
gift of you and André, now that little Gaspard’s place is filled. Give
him to me. Let him take my name. It would be a grief to me to have
it die out. Let there be a new Gaspard Denys growing up into a
brave boy, a good, upright man, we hope. You have your fortune
and André will make another. There will be enough to keep a dozen
children from starving,” with a bright, amused laugh. “I will make a
new will and give the boy what I have left. The lead interest is
increasing and will be a fortune by itself. So if you and André
consent. It is not as if I wanted to take him away; it is simply that
he shall be Gaspard Denys. In the old time they put a St. to it, but
that was in France. We are going to be a new people.”

“Oh, Uncle Gaspard!” and she hid her face on his breast, while her
arms went around his neck. “The best out of my life is hardly good
enough for you. I give you my boy with my whole heart.”

André Valbonais said the same thing. So the Governor and the priest
settled all the legal points, and this, with the certificate of his birth
and baptism and the will of his godfather, Gaspard Denys, were
locked up in a strong box for any time that they might be needed.

A bright, sturdy little fellow was Gaspard, extravagantly fond of his


grandfather and his constant companion. He had his mother’s soft
brown eyes and her curly hair.

One afternoon when the sun had lain warm and golden all about,
Renée Valbonais sat sewing on the wide porch that had been pushed
out large enough for a room. Overhead and at the sides it was a
cluster of vines and blossoming things that shook out fragrance with
every waft of wind. The baby was tumbling about and chattering in
both French and Spanish, for he picked up words easily. Sheba, the
nurse, and Chloe were just outside in the garden. Mère Lunde was
napping in her easy-chair. It was a pretty picture of comfort.

Renée merely glanced up as a young man entered the gate and


looked about him with a touch of uncertainty. Some message from
her husband, doubtless. It was so tranquil they might go out in the
canoe. He came up slowly and then paused, glanced hesitatingly at
her, taking off his cap and bowing. His attire was well worn, but
different from the common habiliments. His figure and air was that
of the cities—she had seen such young men in New Orleans.

“Is it—Madame Valbonais?” he asked.

The voice was cultured and with a peculiar richness. The hand that
held the cap was slim and white as a girl’s. His complexion was clear,
with the faintest suggestion of olive, but rather pale, though the
warmth had given a tint of color to the cheeks.

“I am Madame Valbonais,” gently inclining her head with a charming


graciousness.

“And a De Longueville by birth?”

The accent was such a pure musical French that this time she smiled
as she nodded.

“You do not know—at least you may not remember, but a long while
ago, it seems, you came to Paris and were being sent to the New
World, America. You were at the Hôtel de Longueville, and there
were two little boys——”

“Oh!” she exclaimed, her eyes dilating as a sudden suspicion—


knowledge, indeed—seemed to electrify her. “Oh, you are—” and her
voice failed.

“I am one of the little boys, the eldest, Robert de Longueville. And


my father was your father also. Mine is a sad story, madame, though
it began fair enough. I have come to the New World, where I have
not a friend. All I knew was that you had a grandfather in St. Louis
and were sent thither. You must pardon me, madame——”

His voice broke a little and his eyes were downcast.

The good and tender God had sent some one to her in her hour of
need. She, too, had come a stranger to this new land. But she was
not old enough to realize all the desolation.

Renée rose with gracious courtesy and put out her hand, moved by
her own remembrances as well as his loneliness. He took it and
glanced up. She saw his eyes were brimming with tears. His face
and manner appealed to the tenderest side of her nature, and her
affection went out at once.

“There are no words to thank you for this kindliness, madame. I am


such a stranger to you, although the same blood runs in our veins.
And I speak the truth. Ah, you cannot know——”

“Come and be seated. You look weary. Chloe,” she called, “bring a
glass of wine and some cake.”

Then she pushed a chair up to the small table and put her work in
the pretty Indian basket. His eyes followed the graceful form and
took in the serene, lovely face. Something stirred within him that he
had never known before. He had a French admiration and regard for
his mother, but he could have knelt and kissed the hands of his
sister.

Renée noticed now that his shoes were worn to the ground. He must
have walked far.

“You came from New Orleans?” she ventured.

“Yes. The vessel brought me there. Then a boat was coming up to


Fort Chartres. From there I have walked mostly. I am a poor emigré,
madame. I will not invade your home under false colors. I spent my
last sou to be rowed across the river. But in these troublous times
you must have heard many sad stories.”

“We are largely out of the way. Yes, there have been sad enough
times in France. And your brother——”

“He decided to stay in the monastery, though heaven only knows


how long that will stand. All is terror and wildness, and no one’s life
is safe. My father was—executed——”

“Oh, how terrible!” The tears overflowed her eyes.

The cake and wine came, and, after many thanks, he sipped the
wine, but the cakes he ate like a hungry man. When she would have
sent for more a gesture of his hand retained her.

“I thank you heartily,” he said, with a grave inclination of the head.


“I am such a stranger that I ought to prove my identity. I have
papers——”

“You may show them to my husband. I believe you. Why, I am your


half sister, but with a whole heart, rest assured. Robert de
Longueville. Yes, I remember you both. You were very shy, and I
think I was very much afraid,” smiling as she recalled the old
impressions that seemed like a dream.
“We used to talk of you. We never had any sister of our own. We
were sent to school, and once a year came back to Paris. Papa was
at court. I was a page for awhile, then I went to a military school.
Honoré preferred books and a religious life. He was very sweet and
gentle, while I liked life and stir and adventures. I do not think
mamma quite approved Honoré, but she was proud that I was to be
a soldier. And then the dreadful times began with the mob which
first deprived the King of authority, and then cast him into prison
with hundreds of others. Oh, it was indeed a reign of terror!”

“And your father?” in a low tone.

“They were both cast into prison,” and his voice fell a little. “My
mother died there. It would have been better if my father had died
with her. The Commune hated every vestige of royalty, abolished
titles, confiscated estates. And then poor papa was one of its
victims. Our school was broken up and we were driven into Paris. I
don’t know what our fate would have been, impressed in the army
of the rabble; but I would not have fought for the men who had
murdered my father. I would have died first.”

Renée wiped the tears from her eyes. Until now it seemed as if she
had never cared for her father. Surely he had expiated all mistakes
and sins by his death.

“Then I ran away. I found my way to the monastery and Honoré and
told them the sad tale. They were very kind and would have kept
me, but there was no knowing how long they would be allowed their
refuge. I resolved to escape to England, as every week or two
refugees were flying thither. I found my opportunity. And there I
heard many things about these new United Colonies. The English are
not over-cordial to them, but the thought of a people who had
fought seven years for liberty and conquered in the face of such
odds fired my heart. I resolved to come to America. We had never
forgotten you, madame, and Honoré wrote that if I found you I was
to give you his love. He is a sweet, gentle fellow and will make an
excellent priest, if there is any France left,” he added mournfully,
drawing a long, pained breath.

She was glad they had remembered her and talked of her. She
raised her sweet, sympathetic eyes.

“Then I came to New Orleans, as I learned from there I could reach


St. Louis. It is queer, but all of you on this side of the river are under
Spanish domination, and it is well for you, perhaps, even if you are
French.”

“I know so little about it,” she replied gravely, “only that we are
proud of being French. But the poor King and Queen, and—papa!”

“Honoré and I were thankful mamma died in prison, though we do


not know what she suffered. And that is the whole of the sad story,
madame. I am young and can work for my bread, surely, and it will
not be so lonely since I have found you.”

Her tender heart went out to him. “Monsieur Robert,” she said, “I
hope we shall be good friends. I am glad you came to me——”

“But I do not mean to be a burden on you,” he subjoined quickly. “I


still think I should like to be a soldier, yet I have a fair education and
I can make my living at something.”

In the light of the luxury of Paris all through his childhood, so


differently aspected from this, he gathered that his sister was far
from rich; but even if she had been, he had not meant to ask help
from her. There was a good deal of pride in the De Longueville
blood. He had not come as a suppliant for anything but love. She
liked him none the worse for it. Then glancing up, she saw Uncle
Gaspard and her child in the street.

“Excuse my absence a few moments and go on with your rest, for


you look weary enough. Chloe, bring some more wine and cake.”
Then she glided down the path and met them at the gateway. Her
face was flushed, her eyes deep and full of emotion.

“Come here in the little arbor,” she cried. “A strange thing has
happened to me. I feel as if I had been reading it in a book, but it is
all true. I hardly know where to begin. And, Uncle Gaspard, you
must be kind and merciful, and forgive my father for his neglect. He
is dead. He was one of the victims of that awful revolution because
he was faithful to his King.”

“Renée, child, do not give way to such excitement. The grave covers
all. We do not carry our grudges beyond it. And if he had loved you,
you would never have come to me and I should have lost much,
much!” And, picking up little Gaspard, he kissed him fondly and lifted
him to his shoulder.

“Yes, I knew you would forgive, you are so generous. And”—she


caught his free hand—“my brother, who has fled from those horrible
scenes, who has lost both parents, has emigrated and is here—
found me after some searching. Life has gone hardly with him.”

“Count de Longueville’s son!” The lines of Gaspard Denys’s face


hardened, his eyes grew stern.

“Think of him as my brother only,” she pleaded. “We are to be kindly


disposed to our enemies even. And, as you say, if he had been a
fond father to me you would never have had me or little Gaspard. I
think Robert will soon go away again. He has been partly bred for a
soldier. And we ought not visit on him any sin of his father. That is
left for God.”

“True.” It was gravely said, but not cordially. “Let us see what the
young man is like. Renée, he never shall be any trouble to you.”

“Oh, you will feel so sorry for him presently.”


They walked to the porch—gallery, as every one called it. The young
fellow had finished his food and wine again. He had eaten nothing
since morning. He looked a little rested, but his eyes had a
questioning glance.

He was not quite what Gaspard had looked for in a De Longueville.


Barely medium size, though he was not yet twenty, refined and with
a quiet dignity, he rather disarmed the critical eyes, and Gaspard
experienced a touch of sympathy for him. Renée made him tell his
pathetic story over again, which he did modestly enough. And when
he would have gone, though whither he knew not, Denys bade him
stay. There were no inns in the town.

He won André as well before the evening was over. And when they
found he had no plans, only a vague desire to offer his services to
the new government that in other days had aroused such an interest
in France, they bade him remain with them. He had both seen and
heard the Marquis de Lafayette after his return to France, when he
had been full of enthusiasm for the new people.

“But, Monsieur Robert, you are French,” said André. “And in the
turns of fate we may some day have a French country here.
Anyhow, a man may earn his bread; and from what I hear, the
colonies are not overstocked with prosperity. Better wait awhile and
cast in your lot with us.”

Robert de Longueville was very glad to. He thought of the Reign of


Terror with a shudder, and often wondered about Honoré, hearing at
last that he was safe in an outlying district of northern France.
CHAPTER XXII—A NEW ST. LOUIS

Once again the French flag waved over St. Louis and hearts beat
high with joy. Not that they had been unhappy or discontented
under the Spanish régime, though the place had remained
stationery. Except for the fur trade and the energies of the house of
Maxent Laclede & Co. with their entrepot, it would still have been a
little French hamlet. Even now it had scarcely two hundred buildings
and less than a thousand inhabitants. Yet perhaps few places could
boast of forty years of content and happiness and such peaceful
living.

So down came the Spanish flag and up went the lilies of France.
There was a night of rejoicing. People scarcely went to bed. Fiddles
and flutes played old French airs, and songs were sung; but, after
all, the people were decorous and there was no orgie. Most of these
men had never known Parisian enthusiasm. Robert de Longueville
marvelled at it and the simplicity.

It was well, perhaps, to have had those few hours of jubilation for
men to talk about in their old age. For the next day a company came
over from the fort and held a consultation with Lieutenant-Governor
Dellassus. And then the royal lilies came down slowly, sadly, it
seemed, and men’s hearts beat with sudden apprehension. What did
it mean? They gathered in little knots and their faces were blanched.

Captain Stoddard raised the new colors—broad bands of red and


white and thirteen stars on a blue field. The brave colonies had
taken another leap and crossed the Mississippi. Here at the old
Spanish quarters, March, 1804, the last vestige of hope fluttered and
died in the French heart. The breeze caught the flag and flung it out
and a few cheers went up, but they were from the Americans, and
the salutes even had a melancholy sound.

“St. Louis,” said some one. “Will they take away the name, too? Are
we to be orphans?”

Others wept. Some of the better informed tried to explain, but it was
half-heartedly. No one was certain of what was to come. These
conquerors, yes, they were that, spoke a different tongue, had a
different religion, were aggressive, a resistless power that might
sweep them beyond the mountains.

There was no rejoicing that night. There were no cabarets in which


men could drink and discuss the change. They went to each other’s
houses and sat moodily by firesides. Old St. Louis was lost to them
and hearts were very heavy.

Spain had ceded the whole of Louisiana to France, and again France
had sold her desirable possession. Napoleon, hating the English and
wanting the money to carry on his war against them, had bargained
with the United States. All the great country lying westward no one
knew how far. And the mighty river was free from troublesome
complications.

Yes, old St. Louis was gone. There was something new in the very
air, an energy where there had been a leisurely aspect; a certain
roughness instead of simplicity, pioneer life. No avalanche swept
over them, but people came from the other side of the river, stalwart
boatmen, stalwart hunters, with new and far-reaching ideas.
Schools, poor enough at first, but teaching something besides the
catechism and a little arithmetic. There were books to read,
discoveries to make, mines to unearth, more profitable ways of
labor. The old slow method of work in the salt licks was improved
upon, as well as that of the lead mines. Upper Louisiana held in its
borders some of the great wealth of the world. Spanish language
dropped out, French began to be a good deal mixed, and men found
it to their advantage to learn English. The stockade and the round
towers dropped down, and no one repaired them, because the town
was going to stretch out. New houses were built, but many of them
seemed as queer at a later date, with their second-floor galleries
approached by a stairs from the outside. The high-peaked roofs with
their perky windows looked down on the old one-story houses of
split logs and plaster. Laclede’s town, about a mile long, was old
enough to have legends growing about it when men sat out on
stoops and smoked their pipes.

Yet there was enough of the past left to still afford content and
romance. Robert de Longueville proved himself a capable young
fellow and turned his past education to some account. He had a
truly French adoration for his half sister that presently won quite a
regard from Gaspard Denys.

Robert was fascinated as well with the half Indian wife of M.


Marchand, and never tired of the wild legends of fur hunting and life
up at the strait. Then the ten children were a great source of interest
as well. There were only two girls among them, the boys growing up
tall, strong and fine-looking, proud of their mother, who kept
curiously young and occasionally put on all her Indian finery for their
amusement.

Renée was quite fair and rather petite, and with such shining eyes
they often called her Firefly. Then Robert fell in love with her, and
there was another Renée de Longueville to hand down the name,
and very proud felt Renée Valbonais of the fact.

The little old church was partly rebuilt in the repairing, and was
turned about. Then many years afterward it became the French
Cathedral on Walnut Street. The high, stiff pews savor of olden time.
There are still several paintings in it, one very fine, sent by Louis,
the King of France. And there are the inscriptions in four languages,
two modern and two ancient.
When Renée Valbonais knelt in her pew at the consecration her face
was still sweet, her eyes brown, soft and smiling, but the hair curling
about her forehead was snowy white. On this spot she had prayed
for Uncle Gaspard’s safe return, then she had prayed to be made
willing to give him up if it was for his happiness. Now she had very
little to pray for, so many blessings had been showered upon her by
the good God. So her heart was all one great thanksgiving, and she
felt that at the last she could “depart in peace.”

When it was set off from Louisiana, when it became a Territory and
then a State, St. Louis remained the capital. Brick and finished frame
houses were built, stores and factories, a newspaper started, a
steamboat came up the river, and that revolutionized the trade.

Then it was to change curiously again. The Americans had nearly


superseded the French. Some of them went to the towns below,
intermarriages became common as the prejudices died away. Then
there was a great German emigration. The failure of patriotic hopes
at home in the Old World sent many across to the New World. They
were of the better class, educated, energetic and earnest for
freedom of thought. Again in 1849 they were largely recruited after
another unsuccessful revolution.

Eighty-three years after the founding of the town they held a grand
celebration. Only one member of Pierre Laclede Liquist’s company,
who had planted and named the town, was living. This was the
president of the day, Pierre Chouteau. The fine old madame, who
had gloried in her brave sons, had passed to the other country. Four
mounted Indians in full costume were the bodyguard of the
venerable president, and in the carriages were a few withered-up,
brown-faced Frenchmen, who had made themselves log houses
along those early years and lived their simple lives, raised their
families, danced in the merry-makings and now felt almost like
aliens.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like