O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Functional PHP

Book Description

Uncover the secrets of functional programming with PHP to ensure your applications are as great as they can be

About This Book

  • Greatly improve your code quality, testability, and readability using modern functional programming techniques
  • Get a solid foundation in functional programming techniques and methodologies
  • Step-by-step learn the concepts to architect more robust code

Who This Book Is For

If you are a PHP developer with knowledge of object-oriented programming, this book is for you. You do not need prior experience with functional programming.

What You Will Learn

  • Declare functions/callables and find out how to manipulate and call them
  • Write pure functions to get more robust code that can be easily tested
  • Learn to compose function using various techniques
  • Use a functional approach to find readable solutions to common issues
  • Utilize performance optimization techniques such as laziness, memorization, and parallelization
  • Build the business logic of applications with the functional paradigm
  • Test functional code and know how to speed up test runs using parallel testing
  • Understand the impact and limitation of functional programming in PHP

In Detail

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.

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.

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.

Style and approach

This is an easy-to-follow, definitive guide on developing applications using a functional paradigm with PHP. It will guide you through functional programming with the help of real-life examples.

Downloading the example code for this book. You can download the example code files for all Packt books you have purchased 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 code file.

Table of Contents

  1. Functional PHP
    1. Functional PHP
    2. Credits
    3. About the Author
    4. About the Reviewer
    5. www.PacktPub.com
      1. Why subscribe?
    6. Customer Feedback
    7. Preface
      1. What this book covers
      2. What you need for this book
      3. Who this book is for
      4. Conventions
      5. Reader feedback
      6. Customer support
        1. Downloading the example code
        2. Errata
        3. Piracy
        4. Questions
    8. 1. Functions as First Class Citizens in PHP
      1. Before we begin
        1. Coding standards
        2. Autoloading and Composer
      2. Functions and methods
      3. PHP 7 scalar type hints
      4. Anonymous functions
      5. Closures
        1. Closures inside of classes
      6. Using objects as functions
      7. The Closure class
      8. Higher-order functions
      9. What is a callable?
      10. Summary
    9. 2. Pure Functions, Referential Transparency, and Immutability
      1. Two sets of input and output
      2. Pure functions
        1. What about encapsulation?
        2. Spotting side causes
        3. Spotting side effects
        4. What about object methods?
        5. Closing words
      3. Immutability
        1. Why does immutability matter?
        2. Data sharing
        3. Using constants
        4. An RFC is on its way
        5. Value objects
        6. Libraries for immutable collections
          1. Laravel Collection
          2. Immutable.php
      4. Referential transparency
        1. Non-strictness or lazy evaluation
          1. Performance
          2. Code readability
          3. Infinite lists or streams
        2. Code optimization
        3. Memoization
      5. PHP in all that?
      6. Summary
    10. 3. Functional Basis in PHP
      1. General advice
        1. Making all inputs explicit
        2. Avoiding temporary variables
        3. Smaller functions
        4. Parameter order matters
      2. The map function
      3. The filter function
      4. The fold or reduce function
        1. The map and filter functions using fold
        2. Folding left and right
        3. The MapReduce model
      5. Convolution or zip
      6. Recursion
        1. Recursion and loops
      7. Exceptions
        1. PHP 7 and exceptions
      8. Alternatives to exceptions
        1. Logging/displaying error message
        2. Error codes
        3. Default value/null
        4. Error handler
      9. The Option/Maybe and Either types
        1. Lifting functions
        2. The Either type
      10. Libraries
        1. The functional-php library
          1. How to use the functions
          2. General helpers
          3. Extending PHP functions
          4. Working with predicates
          5. Invoking functions
          6. Manipulating data
          7. Wrapping up
        2. The php-option library
        3. Laravel collections
          1. Working with Laravel's Collections
        4. The immutable-php library
          1. Using immutable.php
        5. Other libraries
          1. The Underscore.php library
          2. Saber
          3. Rawr
          4. PHP Functional
          5. Functional
          6. PHP functional programming Utils
          7. Non-standard PHP library
      11. Summary
    11. 4. Composing Functions
      1. Composing functions
      2. Partial application
      3. Currying
        1. Currying functions in PHP
      4. Parameter order matters a lot!
      5. Using composition to solve real issues
      6. Summary
    12. 5. Functors, Applicatives, and Monads
      1. Functors
        1. Identity function
        2. Functor laws
        3. Identity functor
        4. Closing words
      2. Applicative functors
        1. The applicative abstraction
        2. Applicative laws
          1. Map
          2. Identity
          3. Homomorphism
          4. Interchange
          5. Composition
          6. Verifying that the laws hold
        3. Using applicatives
      3. Monoids
        1. Identity law
        2. Associativity law
        3. Verifying that the laws hold
        4. What are monoids useful for?
        5. A monoid implementation
        6. Our first monoids
        7. Using monoids
      4. Monads
        1. Monad laws
          1. Left identity
          2. Right identity
          3. Associativity
          4. Validating our monads
        2. Why monads?
        3. Another take on monads
        4. A quick monad example
      5. Further reading
      6. Summary
    13. 6. Real-Life Monads
      1. Monadic helper methods
        1. The filterM method
        2. The foldM method
        3. Closing words
      2. Maybe and Either monads
        1. Motivation
        2. Implementation
        3. Examples
      3. List monad
        1. Motivation
        2. Implementation
        3. Examples
          1. Where can the knight go?
      4. Writer monad
        1. Motivation
        2. Implementation
        3. Examples
      5. Reader monad
        1. Motivation
        2. Implementation
        3. Examples
      6. State monad
        1. Motivation
        2. Implementation
        3. Examples
      7. IO monad
        1. Motivation
        2. Implementation
        3. Examples
      8. Summary
    14. 7. Functional Techniques and Topics
      1. Type systems
        1. The Hindley-Milner type system
        2. Type signatures
        3. Free theorems
        4. Closing words
      2. Point-free style
      3. Using const for functions
      4. Recursion, stack overflows, and trampolines
        1. Tail-calls
        2. Tail-call elimination
        3. From recursion to tail recursion
        4. Stack overflows
        5. Trampolines
          1. Multi-step recursion
          2. The trampoline library
        6. Alternative method
        7. Closing words
      5. Pattern matching
        1. Pattern matching in PHP
          1. Better switch statements
          2. Other usages
      6. Type classes
      7. Algebraic structures and category theory
        1. From mathematics to computer science
          1. Important mathematical terms
        2. Fantasy Land
      8. Monad transformers
      9. Lenses
      10. Summary
    15. 8. Testing
      1. Testing vocabulary
      2. Testing pure functions
        1. All inputs are explicit
        2. Referential transparency and no side-effects
        3. Simplified mocking
        4. Building blocks
        5. Closing words
      3. Speeding up using parallelization
      4. Property-based testing
        1. What exactly is a property?
        2. Implementing the add function
        3. The PhpQuickCheck testing library
        4. Eris
        5. Closing words
      5. Summary
    16. 9. Performance Efficiency
      1. Performance impact
        1. Does the overhead matter?
        2. Let's not forget
        3. Can we do something?
        4. Closing words
      2. Memoization
        1. Haskell, Scala, and memoization
        2. Closing words
      3. Parallelization of computation
        1. Parallel tasks in PHP
          1. The pthreads extension
          2. Messaging queues
          3. Other options
        2. Closing words
      4. Summary
    17. 10. PHP Frameworks and FP
      1. Symfony
        1. Handling the request
        2. Database entities
          1. Embeddables
          2. Avoiding setters
          3. Why immutable entities?
          4. Symfony ParamConverter
          5. Maybe there is an entity
        3. Organizing your business logic
        4. Flash messages, sessions, and other APIs with side-effects
        5. Closing words
      2. Laravel
        1. Database results
          1. Using Maybe
        2. Getting rid of facades
        3. HTTP request
        4. Closing words
      3. Drupal
        1. Database access
        2. Dealing with hooks requiring side effects
        3. Hook orders
        4. Closing words
      4. WordPress
        1. Database access
        2. Benefits of a functional approach
        3. Closing words
      5. Summary
    18. 11. Designing a Functional Application
      1. Architecture of a purely functional application
      2. From Functional Reactive Animation to Functional Reactive Programming
        1. Reactive programming
        2. Functional Reactive Programming
          1. Time traveling
          2. Disclaimer
        3. Going further
      3. ReactiveX primer
      4. RxPHP
        1. Achieving referential transparency
      5. Summary
    19. 12. What Are We Talking about When We Talk about Functional Programming
      1. What is functional programming all about?
        1. Functions
        2. Declarative programming
        3. Avoiding mutable state
      2. Why is functional programming the future of software development?
        1. Reducing the cognitive burden on developers
          1. Keeping the state away
          2. Small building blocks
          3. Locality of concerns
          4. Declarative programming
        2. Software with fewer bugs
        3. Easier refactoring
        4. Parallel execution
        5. Enforcing good practices
      3. A quick history of the functional world
        1. The first years
        2. The Lisp family
        3. ML
        4. The rise of Erlang
        5. Haskell
        6. Scala
        7. The newcomers
      4. Functional jargon