1. Go to this page and download the library: Download yohang/finite library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
yohang / finite example snippets
enum DocumentState: string implements State
{
case DRAFT = 'draft';
case PUBLISHED = 'published';
case REPORTED = 'reported';
case DISABLED = 'disabled';
public static function getTransitions(): array
{
return [
new Transition('publish', [self::DRAFT], self::PUBLISHED),
new Transition('clear', [self::REPORTED, self::DISABLED], self::PUBLISHED),
new Transition('report', [self::PUBLISHED], self::REPORTED),
new Transition('disable', [self::REPORTED, self::PUBLISHED], self::DISABLED),
];
}
}
class Document
{
private DocumentState $state = DocumentState::DRAFT;
public function getState(): DocumentState
{
return $this->state;
}
public function setState(DocumentState $state): void
{
$this->state = $state;
}
}
use Finite\StateMachine;
$document = new Document;
$sm = new StateMachine;
// Can we process a transition ?
$sm->can($document, 'publish');
// Apply a transition
$sm->apply($document, 'publish');
enum DocumentState: string implements State
{
// ...
public function isDeletable(): bool
{
return in_array($this, [self::DRAFT, self::DISABLED]);
}
public function isPrintable(): bool
{
return in_array($this, [self::PUBLISHED, self::REPORTED]);
}
}
use Finite\Event\CanTransitionEvent;
use Finite\Event\PostTransitionEvent;
$dispatcher = $stateMachine->getDispatcher();
// 1. Guard: Prevent a transition dynamically
$dispatcher->addEventListener(CanTransitionEvent::class, function (CanTransitionEvent $event) {
if ('publish' === $event->getTransition()->getName() && !$event->getObject()->title) {
// Block the transition if the title is empty
$event->blockTransition();
}
});
// 2. Post-Action: Do something after a transition
$dispatcher->addEventListener(PostTransitionEvent::class, function (PostTransitionEvent $event) {
// e.g. Send an email, log activity...
echo 'Transition ' . $event->getTransition()->getName() . ' completed!';
});