Book Image

Functional PHP

By : Gilles Crettenand
Book Image

Functional PHP

By: Gilles Crettenand

Overview of this book

<p>A functional approach encourages code reuse, greatly simplifies testing, and results in code that is concise and easy to understand. This book will demonstrate how PHP can also be used as a functional language, letting you learn about various function techniques to write maintainable and readable code.</p> <p>After a quick introduction to functional programming, we will dive right in with code examples so you can get the most of what you’ve just learned. We will go further with monads, memoization, and property-based testing. You will learn how to make use of modularity of function while writing functional PHP code.</p> <p>Through the tips and best practices in this book, you’ll be able to do more with less code and reduce bugs in your applications. Not only will you be able to boost your performance, but you will also find out how to eliminate common loop problems. By the end of the book, you will know a wide variety of new techniques that you can use on any new or legacy codebase.</p>
Table of Contents (19 chapters)
Functional PHP
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Preface

Functional programming is a paradigm that is present every year at conferences. The JavaScript community is probably one of the first that approached the subject, but the topic is now also discussed among the developers using various other languages such as Ruby, Python, and Java.

PHP has most of the features that are needed to start using a functional approach for development. You have no reason to be left on the side, which is why this book proposes to teach you the fundamentals of functional programming.

If you are completely new to functional programming or you want to refresh your basics and learn a bit about its history and benefits, I recommend that you start with the appendix. It is not the first chapter of the book as the content is not directly related to PHP, but it will help you put various topics in context and have a better idea of the topics covered in this book.

What this book covers

Chapter 1, Functions as First Class Citizen in PHP, discusses how functional programming, as the name suggests, revolves around functions. In this chapter, you will learn the about the various way they can be declared and used in PHP.

Chapter 2, Pure Functions, Referential Transparency, and Immutability, covers the three concepts that are the cornerstone of any functional code base. You will learn what they are about and how to apply them to our benefit.

Chapter 3, Functional Basis in PHP, discusses how functional programming, like any paradigm, rests upon a few core concepts. This chapter will present them in a simple fashion before going further.

Chapter 4, Composing Functions, describes how functions are often used as a building block using function composition. In this chapter, you will learn how to do it in PHP what it is important to keep in mind when doing so.

Chapter 5, Functors, Applicatives, and Monads, starts with easier concepts, such as the functor and the applicative, and we will build up our knowledge to finally present the monad in a light that should dispel some of the fear floating around this term.

Chapter 6, Real-life Monads, helps you learn about some real-life usage of the monad abstraction and how it can be used to write better code.

Chapter 7, Functional Techniques and Topics, brushes upon topics such as type systems, pattern matching, point-free style, and others from the vast field of functional programming.

Chapter 8, Testing, teaches you that functional programming not only helps with writing code that is easier to understand and maintain, but it is also great to facilitate testing.

Chapter 9, Performance Efficiency, lets you know that using functional techniques in PHP has a cost. We will first discuss it and then see how it can help in other performance-related topics.

Chapter 10, PHP Frameworks and FP, introduces a technique that can be applied to improve your code in any project, as there is currently now dedicated framework for functional programming in PHP.

Chapter 11, Designing a Functional Application, will present you with some advice if you want to develop a whole application using the most functional code possible. You will also learn about Functional Reactive Programing and the RxPHP library.

AppendixWhat are We Talking about When We Talk about Functional Programming?, is a presentation and history of functional programming alongwith its benefits and a glossary. It’s really the first part of the book you should read, but as we don’t approach the subject from the PHP angle, it is presented as an appendix.

What you need for this book

You will need to have access to a computer with PHP installed. It will be easier if you know how to use the command line, but all examples should also work in a browser with maybe some small adaptations.

While learning functional programming, I also recommend the usage of a Read-Eval-Print-Loop (REPL). I personally used Boris when writing this book. You can find it at https://github.com/borisrepl/boris. Another great option is PsySH (http://psysh.org).

Although not at all mandatory, a REPL will allow you to quickly test your ideas and play around with the various concepts that will be presented in this book without having to juggle between your editor and command line.

I also assume you have Composer available and that you know how to use it to install new packages; if not, you can find it at https://getcomposer.org. Multiple libraries will be presented throughout the book and the preferred way to install them is using composer.

All the code written in the book was tested on PHP 7.0, which is the de facto recommended version. It should, however, also run on any newer version. Running most of the examples should also be fine on PHP 5.6 after making some minor adaptations. We will use the new scalar type hinting feature introduced in PHP 7.0 throughout the book, but if you remove those, the code should be readily compatible with lower versions.

Who this book is for

This book requires no knowledge of functional programming; prior programming experience is, however, required. Also, basic concepts from object-oriented programming will not be covered in depth.

Deep knowledge of the PHP language is not mandatory, as uncommon syntax will be explained. The book should be understandable to someone who hasn't written a single line of PHP code, with some effort.

This book can be considered as a beginner book about functional programming in PHP, meaning that we will build knowledge incrementally. However, the topic being pretty vast and the limited page count, we will move quickly at times. This is why I encourage you to play with the variously presented concepts as we learn them and take some time at the end of each chapter to make sure you understood it correctly.

Conventions

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

Code words in the text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The next lines of code read the link and assign it to the BeautifulSoup function."

A block of code is set as follows:

<?php
function getPrices(array $products) {
  $prices = [];
  foreach($products as $p) {
    if($p->stock > 0) {
      $prices[] = $p->price;
    }
  }
  return $prices;
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<?php
function getPrices(array $products) {
  $prices = [];
  foreach($products as $p) {
    if($p->stock > 0) {
      $prices[] = $p->price;
    }
  }
  return $prices;
}

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

composer require rx/stream

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

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

Downloading the example code

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

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.

  2. Hover the mouse pointer on the SUPPORT tab at the top.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box.

  5. Select the book for which you're looking to download the code files.

  6. Choose from the drop-down menu where you purchased this book from.

  7. Click on Code Download.

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

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux

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

Errata

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

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

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

Please contact us at [email protected] with a link to the suspected pirated material.

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

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.