THE STATEFUL ELEPHPANT
RICK KUIPERS / @RSKUIPERS
@PHPSTORMTIPS
STATE
CODE EXAMPLE
THE STATE PATTERN
CODE EXAMPLE
THE STATE STRATEGY PATTERN?
STRATEGY PATTERN
! Tries to achieve similar result for input
! Strategies can’t transition to otherstrategies
! Strategy processes the input and givesoutput back to the wrapper
STATE PATTERN
! Result can be completely different
! States can trigger transitions to otherstates
! State controls the behaviour of itscontext object (ElePHPant)
WHY SHOULD WE CARE?
CHECKOUT
PAYMENTDETAILS REVIEW
CODE EXAMPLE
PROS
! Independent blocks of logic
! Easy to add new states without touching existing code
! Can easily be coordinated
THE STATE MACHINE
THE STATE MACHINE
Ileft Iright Idown Iup Ispace
Sidling Srunning Srunning Scrouching Sjumping Ashoot
Srunning - - Scrouching Sjumping Ashoot
Sjumping - - - - -
Scrouching - - - - -
THE STATE MACHINE
Input Current State Next State Output
le0 Sidling Srunning -
right Sidling Srunning -
up Sidling Sjumping -
space Sidling Sidling Ashoot
STATUSES
PENDINGNEW COMPLETED CANCELED REFUNDED
CODE EXAMPLE
PROS
! Our transitions are set in stone
! Centralised approach makes callbacks easy
! Good overview of all possible transitions
PACKAGES
DON’T REINVENT THE WHEEL
! https://github.com/winzou/state-machine
! https://github.com/Sylius/SyliusFlowBundle
! https://github.com/rskuipers/stateful-elephpant
! https://github.com/rskuipers/stateful-elephpant-talk
Top Related