Monads in PHP
Hi, I'm Chris
Based on the work of
Tom Stuart
Monads are an ordinary
data type...
...you're probably
already using them.
What is a stack?
Operations and rules
Operations
Stack→push(mixed $value): Stack Stack→pop(): Stack Stack→top(): mixed Stack→isEmpty(): bool
Rules
$stack→push($value)→top() == $value $stack→push($value)→pop() == $stack $stack→push($value)→isEmpty() == false (new Stack)→isEmpty() == true
We can implement these however we like...
ArrayStack
LinkedListStack
We can define
more operations...
Stack Size Method
Stack is a specification
common interface
shared functionality
What is a Collection?
Operations and rules
Operations
Collection→each(callable $func)
Rules
$collection→each($func)
calls $func zero or more times,
in sequence, with a value each time
We can (again) implement these however we like...
ArrayCollection
RangeCollection
We can (again) define
more operations...
Collection Filter Method
Collection is a
specification
common interface
shared functionality
What are stack and collection?
They are
Abstract Data Types
Let's refactor...
Handling null
Handling null
Handling many
Handling many
Why are we doing this?
Similar things
Maybe and Many
are Monads
They are an
Abstract Data Type
Operations and rules
Operations
Monad→then(callable $func)
Monad→create(...$params)
Rules
$monad→then(callable $func)
calls $func zero or more times, always returns instance of same monad
$monad→create(mixed $value)
Doesn't alter the value
Monad is a
specification
common interface
shared functionality
We use then to connect multiple operations...
Maybe: do the next thing
if value is not null
Many: do the next thing
for each value
We can (again) define
more operations...
Monad Within Method
Where are we
already using this?
$(".cart")
.filter(".checkout")
.on("click", onCheckoutClick);
DB::table("users") →where("name", "=", "John")
→orWhere(function($query) { $query
→where("votes", ">", 100)
→where("title", "!=", "Admin"); });
Monads are good for
chaining operations
Maybe: chain the
null-checking
Many: chain
flatMap
Promise: chain
functions to be called
with eventual values
jQuery: chain filter
and modify elements
in the DOM
Fluent: chain
changes to a query
When you see yourself chaining operations...
...think how you could be using a Monad-like thing
...try to use Monads
...and tell your friends
about them
Thanks
twitter.com/assertchris
slides.com/assertchris
youtube.com/assertchris