SlideShare a Scribd company logo
1 of 63
Download to read offline
Being functional in PHP
David de Boer14 May 2016
functional
functions
y = f(x)
f: X → Y
functional programming
functional thinking
functional communication
not languages
Why should you care?
f(x)
Others
PHP
C++
C
Java
– Robert C. Martin
“There is a freight train barreling
down the tracks towards us, with
multi-core emblazoned on it; and
you’d better be ready by the time
it gets here.”
λ
closures
__invoke
2001 2009 2011 2012
array_map
array_filter
callable
Slim
Silex
middlewaresSymfony2
2013 2014 2015 2016
PSR-7
anonymous
classes
foreach
promises
futuresStackPHP
“The limits of my language
mean the limits of my world.”
– Ludwig Wittgenstein
I’m David
/ddeboer
@ddeboer_nl
Erlang: The Movie
Erlang
Concurrent
Passing messages
Fault-tolerant
Let’s begin$ brew install erlang
$ erl
Erlang/OTP 18 [erts-7.2.1] [source] [64-bit] [smp:4:4] [async-threads:
10] [hipe] [kernel-poll:false] [dtrace]
Eshell V7.2.1 (abort with ^G)
1>
on OS X
REPL
➊
<?php
$sum = 0;
for ($i = 1; $i <= 5; $i++) {
$sum = $sum + $i;
}
echo $sum;
// 15
-module(math).
-export([sum/1]).
sum(Number) ->
Sum = 0,
Numbers = lists:seq(1, Number),
lists:foreach(
fun(N) ->
Sum = Sum + N
end,
Numbers
),
Sum.
math:sum(5).
no return
keyword
** exception error: no match
of right hand side value 1
1> X = 5.
5
2> X.
5
3> X = X * 2.
** exception error: no match of right hand side value 10
4> 5 = 10.
** exception error: no match of right hand side value 10
but isn’t
looks like
assignment
1> lists:sum(lists:seq(1, 5)).
15
➋
Imperative<?php
$sum = 0;
for ($i = 1; $i <= 5; $i++) {
$sum = $sum + $i;
}
iteration
keeps
changing
-module(math2).
-export([sum2/1]).
sum2(Number) ->
List = lists:seq(1, Number),
sum2(List, 0).
sum2([], Sum) -> Sum;
sum2([H|T], Sum) -> sum2(T, H + Sum).
3> math2:sum(5).
15
empty list
separate head from tail recurse
pattern
matches
generate list
Declarative 1<?php
// Declare a function!
function sum($x)
{
if ($x == 0) {
return $x;
}
return $x + sum($x - 1);
}
sum(5);
// still 15
$x never
changes
recursion
Declarative 2<?php
function sum2($number)
{
array_sum(range(1, $number));
}
echo sum2(5);
// yuuuup, 15 again
functionfunction
composition
Some history
Church Von Neumann
declarative imperative
A lot of our code is about the
hardware it runs on
But programmers should worry

about the conceptual problem domain
Recursion-module(math).
-export([fac/1]).
fac(0) -> 1;
fac(N) -> N * fac(N - 1).
1> math:fac(9).
362880
Recursion fail-module(math).
-export([fac/1]).
fac(0) -> 1;
fac(N) -> N * fac(N - 1).
%%fac(9) = 9 * fac(9 - 1)
%% = 9 * 8 * fac(8 - 1)
%% = 9 * 8 * 7 * fac(7 - 1)
%% = 9 * 8 * 7 * 6 * fac(6 - 1)
%% = 9 * 8 * 7 * 6 * 5 * fac(5 -1)
%% = 9 * 8 * 7 * 6 * 5 * 4 * fac(4 - 1)
%% = 9 * 8 * 7 * 6 * 5 * 4 * 3 * fac(3 - 1)
%% = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * fac(2 - 1)
%% = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 * fac(1 - 1)
%% = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 * 1
%% = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
%% = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2
%% = 9 * 8 * 7 * 6 * 5 * 4 * 6
%% = 9 * 8 * 7 * 6 * 5 * 24
%% = 9 * 8 * 7 * 6 * 120
%% = 9 * 8 * 7 * 720
%% = 9 * 8 * 5040
%% = 9 * 40320
%% = 362880
10 terms in
memory
Tail recursion-module(math).
-export([tail_fac/1]).
tail_fac(N) -> tail_fac(N, 1).
tail_fac(0, Acc) -> Acc;
tail_fac(N, Acc) -> tail_fac(N - 1, N * Acc).
tail_fac(9) = tail_fac(9, 1).
tail_fac(9, 1) = tail_fac(9 - 1, 9 * 1).
tail_fac(8, 9) = tail_fac(8 - 1, 8 * 9).
tail_fac(7, 72) = tail_fac(7 - 1, 7 * 72).
tail_fac(6, 504) = tail_fac(6 - 1, 6 * 504).
tail_fac(5, 3024) = tail_fac(5 - 1, 5 * 3024).
…
tail_fac(0, 362880) = 362880
do calculation
before recursing
➌
$object->setFoo(5);
$value = $object->getFoo();
no
return
value
no input
value
$object->setFoo(5);
$value = $object->getFoo();
$object->setFoo('Change of state!');
$value = $object->getFoo();
no
return
value
no input
value
same argument,
different return value
No side-effects
A pure function
does not rely on data outside itself
does not change data outside itself
Object orientation
Solve problems with objects
Objects have internal state
Modify state through methods
With side-effectsclass Todo
{
public $status = 'todo';
}
function finish(Todo $task)
{
$task->status = 'done';
}
$uhoh = new Todo();
$uhoh2 = $uhoh;
finish($uhoh);
echo $uhoh->status; // done
echo $uhoh2->status; // done???
No side-effectsclass Todo
{
public $status = 'todo';
}
function finish(Todo $task)
{
$copy = clone $task;
$copy->status = 'done';
return $copy;
}
$uhoh = new Todo();
$finished = finish($uhoh);
echo $finished->status; // done
echo $uhoh->status; // todo
cloning is
cheap
Some state 

must change
Read/write database
Get user input
Current date and time
Random values (security)
Immutable objects
PSR-7 HTTP messages
Domain value objects
DateTimeImmutable
Service objects
➍
Higher-order functions
Functions are values
so they can be arguments
and return values
$names = ['Billy', 'Bob', 'Thornton'];
$anonymise = anonymise('sha256');
var_dump(array_map($anonymise, $names));
// array(3) {
// [0]=>
// string(64) "85eea4a0285dcb11cceb68f39df10d1aa132567dec49b980345142f09f4cb05e"
// [1]=>
// string(64) "cd9fb1e148ccd8442e5aa74904cc73bf6fb54d1d54d333bd596aa9bb4bb4e961"
// [2]=>
// string(64) "d7034215823c40c12ec0c7aaff96db94a0e3d9b176f68296eb9d4ca7195c958e"
// }
using PHP built-ins
$names = ['Billy', 'Bob', 'Thornton'];
$anonymise = anonymise('sha256');
var_dump(array_map($anonymise, $names));
// array(3) {
// [0]=>
// string(64) "85eea4a0285dcb11cceb68f39df10d1aa132567dec49b980345142f09f4cb05e"
// [1]=>
// string(64) "cd9fb1e148ccd8442e5aa74904cc73bf6fb54d1d54d333bd596aa9bb4bb4e961"
// [2]=>
// string(64) "d7034215823c40c12ec0c7aaff96db94a0e3d9b176f68296eb9d4ca7195c958e"
// }
function anonymise($algorithm)
{
return function ($value) use ($algorithm) {
return hash($algorithm, $value);
};
}
higher-order function
closure
using PHP built-ins
function as value
function as argument
Middleware<?php
use PsrHttpMessageRequestInterface;
function add_header($header, $value)
{
return function (callable $handler) use ($header, $value) {
return function (
RequestInterface $request,
array $options
) use ($handler, $header, $value) {
$request = $request->withHeader($header, $value);
return $handler($request, $options);
};
};
}
$myStack = (new MiddlewareStack())
->push(add_header('Silly-Header', 'and its value'));
call next

in stack
immutable
higher-order function
Middleware<?php
use PsrHttpMessageServerRequestInterface as Request;
use PsrHttpMessageResponseInterface as Response;
$app = new SlimApp();
$app->add(function (Request $request, Response $response, callable $next) {
$response->getBody()->write('Hey there, ');
$response = $next($request, $response);
$response->getBody()->write('up?');
return $response;
});
$app->get('/', function ($request, $response, $args) {
$response->getBody()->write('what’s');
return $response;
});
$app->run();
// Hey there, what’s up?
stream is not 

immutable
before
after
➎
Composition over
inheritance
Service objects<?php
namespace SymfonyComponentSecurityCore;
interface SecurityContextInterface
{
public function getToken();
public function isGranted($attributes, $object = null);
}
Service objects<?php
namespace SymfonyComponentSecurityCoreAuthenticationTokenStorage;
interface TokenStorageInterface
{
public function getToken();
}
namespace SymfonyComponentSecurityCoreAuthorization;
interface AuthorizationCheckerInterface
{
public function isGranted($attributes, $object = null);
}
single function
Single responsibility
taken to its
logical conclusion
You may not need
all those patterns
Take-aways
Reduce and isolate side-effects
Create immutable value objects
Be declarative
More?
Thanks!
https://joind.in/talk/bc26a
@ddeboer_nl

More Related Content

What's hot

Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 

What's hot (20)

Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
 
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
PHP Language Trivia
PHP Language TriviaPHP Language Trivia
PHP Language Trivia
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix Task
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
The best language in the world
The best language in the worldThe best language in the world
The best language in the world
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
 
Programmation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScriptProgrammation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScript
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmer
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 

Viewers also liked

Viewers also liked (14)

PHP 7 new engine
PHP 7 new enginePHP 7 new engine
PHP 7 new engine
 
PHP 7 performances from PHP 5
PHP 7 performances from PHP 5PHP 7 performances from PHP 5
PHP 7 performances from PHP 5
 
PHP, Under The Hood - DPC
PHP, Under The Hood - DPCPHP, Under The Hood - DPC
PHP, Under The Hood - DPC
 
Internet of Things With PHP
Internet of Things With PHPInternet of Things With PHP
Internet of Things With PHP
 
PHP Optimization
PHP OptimizationPHP Optimization
PHP Optimization
 
Php internal architecture
Php internal architecturePhp internal architecture
Php internal architecture
 
Php
PhpPhp
Php
 
PHP WTF
PHP WTFPHP WTF
PHP WTF
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1
 
Php 101: PDO
Php 101: PDOPhp 101: PDO
Php 101: PDO
 
How PHP Works ?
How PHP Works ?How PHP Works ?
How PHP Works ?
 
[Community Open Camp] 給 PHP 開發者的 VS Code 指南
[Community Open Camp] 給 PHP 開發者的 VS Code 指南[Community Open Camp] 給 PHP 開發者的 VS Code 指南
[Community Open Camp] 給 PHP 開發者的 VS Code 指南
 
LaravelConf Taiwan 2017 開幕
LaravelConf Taiwan 2017 開幕LaravelConf Taiwan 2017 開幕
LaravelConf Taiwan 2017 開幕
 
Route 路由控制
Route 路由控制Route 路由控制
Route 路由控制
 

Similar to Being functional in PHP (PHPDay Italy 2016)

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
Moriyoshi Koizumi
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
Sri Prasanna
 

Similar to Being functional in PHP (PHPDay Italy 2016) (20)

Being functional in PHP
Being functional in PHPBeing functional in PHP
Being functional in PHP
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVM
 
Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)
 
Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVM
 
Eta
EtaEta
Eta
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
CppTutorial.ppt
CppTutorial.pptCppTutorial.ppt
CppTutorial.ppt
 
Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, code
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Groovy
GroovyGroovy
Groovy
 
Let's build a parser!
Let's build a parser!Let's build a parser!
Let's build a parser!
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScript
 
C c++-meetup-1nov2017-autofdo
C c++-meetup-1nov2017-autofdoC c++-meetup-1nov2017-autofdo
C c++-meetup-1nov2017-autofdo
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
 
Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?
 

Recently uploaded

Recently uploaded (20)

AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

Being functional in PHP (PHPDay Italy 2016)