Functionalprogramminginphp Sample
Functionalprogramminginphp Sample
Acknowledgement 8
Book Contents 9
Requirements 11
Target Audience 12
Preface 13
2
Contents
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3
Functional Programming in PHP: A Sim-
ple, Concise Primer
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean
Publishing process. Lean Publishing is the act of publishing an in-progress ebook
using lightweight tools and many iterations to get reader feedback, pivot until you
have the right book and build traction once you do.
4
About the Author
Aside from writing code, Mr. Lochemem writes articles he publishes to his blog
hosted on Medium and is profoundly interested in many things: rap music, basket-
ball, soccer, books, video games, as well as podcasting to mention but a few.
5
About the Reviewers
Mr. Cees-Jan Kiewiet is a Senior engineer at Usabilla and core maintainer of React-
PHP. Based in the Netherlands, he has over fifteen years of programming experience
and is proficient in, besides PHP, Golang, and Java. Mr. Kiewiet loves to play video
games, meet with developers at meetups, and bask in the tranquility of his garden
when he is not breaking servers.
6
Chun Sheng-Li
Mr. Li is a Taiwanese engineer who holds both a Master’s and Bachelor’s degree
in Computer Science. He is an open-source enthusiast and avid contributor to
multiple projects. Mr. Li has many programming interests that include web security,
JavaScript, and Blockchain. He currently works as a backend engineer in his native
Taiwan.
7
Acknowledgement
There are many deserving of praise for this monumental effort - my maiden foray
into authorship. First, the reviewers of the book whose secondary appraisal of the
material is more than apt. Second, the developers I collaborate with: the interactions
I have with them has only expedited the finality of this outcome. Third, the creator
of the book artwork, Sam Njuguna, a talented visual artist and USIU-Africa alum.
Fourth, my mentors Paul Bombo, and Dr. Patrick Kanyi Wamuyu. The former is a
cerebral engineer and visionary whose ideas I have developed a reverence for in the
three years I have known him; the latter is a college professor whose teachings have
proved to be insightful. Fifth is USIU-Africa staffer, Dan Muchai - a wise polymath
and good friend.
Finally, my family - all two parents and three siblings of it. I appreciate all the
encouragement they have offered - financial and emotional - since I embarked on
writing the book. I am grateful for the concern my father, Prof. Bruno Ocaya, sisters,
Consolate, Faith and Frances, have shown throughout the writing process and the
unrelenting support my mother, Bernadette Ocaya has imbued in nurturing my
nascent potential.
8
Book Contents
Functional Programming Core Concepts, brings to focus the idea of writing pure
functions, immutability as a concept, and grading functions based on referential
transparency.
Functors, focuses on the Functor construct. It offers an insight into Category Theory,
demonstrates how to roll out functors in PHP, and explains monads of various kinds
- IO, State, Reader, and List.
Parallelization of tasks in PHP, offers insights into achieving concurrency via task
parallelization in PHP using RabbitMQ, PCNTL routines, and the PECL pthreads
9
extension.
10
Requirements
Principally, many versions of PHP, supported and otherwise, can aid in making the
most of the material in this opus. More recent releases of the language (7 and newer)
are, however, better suited to applying Functional Programming principles as they
are better maintained and widely industry-prescribed. I, therefore, recommend
that you the reader install any of the newer supported releases of the language.
Consider downloading Composer, the de-facto dependency manager for PHP, to go
with your chosen PHP variant to operationalize all the programs in the book that
warrant its usage.
I urge that you give heed to the varied chapter requirements from Packagist-hosted,
Composer-installable libraries to PHP language extensions and job worker tools.
The code that features throughout the volume is also available for download: it is
hosted on Github in the repository fp-php-book.
Lastly, I advise that you have an arbitrarily chosen dependable text editor installed
on your system to cater for any tinkerings with any of the code in the subsequent
text.
11
Target Audience
I have written this book with intermediate to advanced developers with PHP expe-
rience in mind. Better suited for the contents of this book are those interested in
adopting a new paradigm, the Functional Programming style.
12
Preface
This book is an attempt to break down the arcane verbiage of the Functional Pro-
gramming discourse while demonstrating its effectiveness in writing readable,
parsable PHP code. PHP is still really popular and has a nexus of communities with
varied interests that galvanize around many paradigms, mostly those not exclusively
of the Functional Programming ilk. Functional Programming is, as emphasized in the
previous paragraph, not only possible in PHP because of its various long-standing
features and all-around improvements, but also adaptable as a cognitive-burden
reducer. I hope that the eight chapters of this volume prove to be more enlight-
ening than uninstructive and dispel various fallacies associated with Functional
Programming while advertising the robustness of PHP.
13
An Introduction to Functional Pro-
gramming in PHP
The desired features extended the scope of the templating language and once
implemented, rendered it business-logic affable. PHP has, over the years im-
proved through each versioned iteration - a progression from version 2.0 to 3.0,
co-authored by Andi Gutmans and Zeev Suranski which looks a lot more like the
version written today was followed by transitions from version 4.0 to 5.0 and then
to 7.0 onwards.
14
A Brief History of Functional Programming
Interesting to note is that PHP did not have a proper specification till 2014. A
specification, a canonical blueprint containing natural language, mathematical,
as well as programmatic expressions of a language’s capabilities is vital to the
programming lifecycle. PHP’s specification can be found online, at https://php.net.
The roots of Functional Programming are traceable to the seminal works of sci-
entists Alonzo Church and Alan Turing. Church’s Lambda Calculus and Turing’s
Universal Machine - both formalized sometime in the 1930s - form the very foun-
dation of Functional Programming. Church advanced - through his Calculus, a
proto-Functional syntax: one that emphasizes the principles of abstraction and
generalization. Turing’s conceit was an emulation of a computing device capable of
transforming calculable inputs - typically those used in human-performable logic
operations - into outputs.
In the 70s, when more procedural and Object-Oriented strategies became more
commonplace, Functional Programming ceded its popularity to the likes of C and
Smalltalk. The popularity of Functional Programming only continued to decline in
the following decades as runtimes like C++ and Java made significant headway in
programming circles. The paradigm was, before a more recent resurgence, effec-
tively pushed to the mainstream periphery and academia. The latter is the arena
in which Haskell - arguably one of the more notable pure Functional programming
15
Defining Functional Programming
The legacies of Alonzo Church’s Lambda notation and Turing’s analytical machine
live on - universally. In PHP, in particular, the first-class function support and
expressive syntax align well with the conceit of capturing the computational aspects
of functions.
16
Functional Programming is a Declarative Paradigm
Please do not conflate abstraction with a total lack of complexity, as that would
be misconstruing the idea altogether. Complexity, according to the concept, should
be neatly tidied away and not removed from code as that would defeat the purpose
17
The Benefits of Functional Programming
Expressions are blocks of code that evaluate to a value. They typically take on the
form of one of either function calls, or operations with any number of operands. It
is possible to write many expressions in PHP: the following are examples.
1 2 * 2;
2 array_filter(range(1, 5), fn (int $x): bool => $x % 2 == 0);
3 'foo' . 'bar';
4 SplFixedArray::fromArray(['foo', 'baz']);
Functional programming reduces the cognitive burden of writing code. The mental
effort required to perform tasks is lessened by composing pure functions.
There exists a variably small, fixed number of shared memory resources in the
human brain for discrete working memory quanta. Working memory, that is, short-
term memory optimized for transient storage, is a limited resource. Each variable
written in a computer program occupies at least one quantum of available memory.
In the snippet below, there are three variables declared and evaluated by the PHP
interpreter.
1 $first = 2;
2 $second = 3;
3 $third = $first + $second; // evaluates to 5
18
Relevance to a PHP Developer
The anonymous add function assigned to the add variable eliminates the need for the
variables named first and second - the lambda function above effectively frees up
working memory and renders the problem of adding two numbers tractable. An arti-
cle written by Eric Elliott, a brilliant technologist, clearly highlights the ameliorative
powers of Functional Programming - I suggest you peruse it.
Naturally, cognitively amenable code is easy to evaluate, transform, and test. Fur-
thermore, functional code is easy to split among multiple processors the goal of
which is often concurrent parallelization (see Chapter 6). It is therefore clear that
Functional Programming’s many advantages stem from its ability to attenuate cog-
nitive load.
Further still, PHP like most multi-paradigm runtimes, not only has first-class function
support, but also simulates a Turing machine (see Appendix): it is an apt enabler of
Functional Programming. The major implication of first-class citizenry is multiplicity-
of-use. PHP’s functions, discussed in great detail in Chapter 2, are manipulable
to the extent of being usable in a variety of contexts: as arguments and return
values as well as variable-assignable entities. Being Turing complete means that
19
Functional Programming in Other Contexts
PHP allows for logic construction via formalized syntax: the language is, by design,
Functional Programming-compliant.
Said tools mirror the functionality of functional languages and are, in many ways,
embellishments of the Lambda Calculus: the said faculties continue to pervade
various eco-systems, reaching multiple programmers and impacting many product
design decisions. The various PHP-exclusive Functional Programming toolkits set
to feature throughout the text should prove immensely useful in harnessing the
paradigm’s cogencies.
Also, the litany of Functional Programming perks enumerated and alluded to in the
previous section is another definite impetus for exploration of Functional Program-
ming’s offerings. Not only is Functional Programming a different approach to writing
code, but it is also soundly organized.
This sub-chapter might be a big red herring considering the focus of the book is
PHP. I do, however, intend to by showing how the paradigm has permeated through
other languages, the popularity of Functional Programming.
JavaScript, yet another scripting language for the web, has soared recently in
popularity. Many web utilities are either languages that transpile to JavaScript or
frameworks written in idiomatic JavaScript. PureScript, a functional language, is
Haskell-esque and compiles to JavaScript. As of the time of writing, the language’s
20
Functional Programming in Other Contexts
GitHub popularity stands at over six-thousand stars. PureScript code looks a lot
like this:
1 import Prelude
2 import Control.Monad.Eff.Console (log)
3
4 greet :: String -> String // greet function type signature
5 greet name = "Hello, " <> name <> "!" // greet function declaration
6
7 main = log(greet "World") // prints "Hello World!"
21
Functional Programming in Other Contexts
Python, a multi-purpose scripting language, also has support for Functional Pro-
gramming. The potency of Python is such that it offers multi-paradigm support
in addition to powering a multitude of technologies like Reddit and Spotify. As far
as Python is concerned, utilities like the pytoolz Functional Programming library
are particularly intriguing. The allure of pytoolz and its conceptual counterparts
like underscore.js and Ruby’s enumerable is the classification of actions - function
genealogies based on iterables, higher-order functions, as well as dictionaries are
immanent in pytoolz’s design. The boilerplate below is that of a simple curry action:
22
Functional Programming in Other Contexts
If you are reading the third version of this opus, you are probably already familiar
with PHP versions 7.4 and newer. The performance and syntax improvements
in the aforestated versions are proof of the language’s continued improvement.
As regards Functional Programming, PHP’s new short closure syntax, first-class
callable syntax, and typed properties present the most straightforward value. Short
closures, in situations that warrant their usage, reduce the verbosity of program
code. First-class callable syntax makes shuttling functions with multiple arguments
an easier proposition. Typed properties enforce strictness inside class contexts
and enhances class code readability. Other features like preloading and the Foreign
Function Interface (FFI) present performance improvements and might require
finesse to operationalize.
23
Summary
Summary
The material in all subsequent chapters is pertinent so far as to familiarize you, the
reader, with Functional Programming constructs - everything from the rudiments
to more advanced constructs - and their application in PHP.
24
Functional Programming Core Con-
cepts
Functions
Functions are at the epicenter of Functional Programming. They are ideal for the
paradigm because they do not possess a history of any kind and have a default
invariable status. Functions are relationships between inputs and outputs - they
are composed of a signature, and posses an arity. Functions are predisposed to
accept arguments, values intended for transformation, the number of which is the
arity. A function signature is a stipulation of return types, argument types, as well
as the encapsulated function logic. Mathematics enables one to define functions.
The snippet below shows how:
f (x) = x + 1
f (2) = 3
25
Functions
f (3) = 4
The function in the snippet which has an arity of 1 is one which increments the
value of the parameter x by 1. x is effectively a placeholder for the transformation
predicated on the addition operation defined. Different results are obtained for
different values of x because the function offers localized computation. Each result
is, therefore, unique to each input.
1 // php function
2 function subtract(int $x, int $y) : int
3 {
4 return $x - $y;
5 }
6
7 subtract(3, 2); // evaluates to 1
Named functions in PHP like the one above are no different (outside of a few syntactic
differences) from those defined in other programming languages. They typically
feature an arbitrary name sandwiched between a function keyword and an ar-
gument list followed by a discretionary signature whose constituents are state
transformation artifacts.
26
Functions
The last type of function in PHP is the class method encapsulated within the scope
of a class. Classes are important in Functional Programming: their significance is
the focus of chapters 4 and 5.
1 class Operations
2 {
3 private $x;
4
5 private $y;
27
Functions
6
7 public function __construct(int $x, int $y)
8 {
9 $this->x = $x;
10 $this->y = $y;
11 }
12
13 public function add() : int
14 {
15 return $this->x + $this->y;
16 }
17 }
18
19 $op = new Operation(1, 2);
20
21 var_dump($op->add()); // evaluates to 3
Setters are absent in the snippet above. The toxicity of setters lies in their high
propensity for function impurity. Henceforth, all ideas of class setters should be
jettisoned. . . .
28
Message to Prospective Readers
This segment concludes the sample opus. If you feel enthused enough by the subject
matter in this book to buy the full edition, please proceed to do so. Regardless of
the purchase decision you make, I hope the elucidatory text you have read thus
far provides the impetus for further engagement with the book’s contents and the
paradigm as a whole.
Buyers of the full version will get access to the remainder of the volume that of-
fers insights into Composition, paradigm-affable error-handling, Category Theory,
Functors, and much more.
Best regards,
29