PHP code example of rokde / state-machine

1. Go to this page and download the library: Download rokde/state-machine 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/ */

    

rokde / state-machine example snippets


// ArticleState should be an Enum/BackedEnum or string constants
enum ArticleState {
    case Draft;
    case InReview;
    case Scheduled;
    case Published;
    case Archived;
}
// ArticleEvent should be an Enum/BackedEnum or string constants
enum ArticleEvent {
    case Submit;
    case Approve;
    case Publish;
    case Update;
    case Archive;
}

$article = new Article();// this is your context

$articleRegistry = new \Rokde\StateMachine\TransitionRegistry();
$articleRegistry->addTransition(
    ArticleState::Draft, ArticleEvent::Submit, ArticleState::InReview,
    guard: fn($article) => $article->hasRequiredMeta(),
)->addTransition(
    ArticleState::InReview, ArticleEvent::Approve, ArticleState::Scheduled,
    guard: fn($article) => $article->published_at > now(),
)->addTransition(
    ArticleState::Scheduled, ArticleEvent::Publish, ArticleState::Published,
    guard: fn($article) => $article->published_at === null || $article->published_at <= now(),
)->addTransition(
    ArticleState::Draft, ArticleEvent::Update, ArticleState::Draft,
    guard: fn($article) => $article->author_id === currentUserId(),
)->addTransition(
    ArticleState::InReview, ArticleEvent::Update, ArticleState::Draft,
    guard: fn($article) => $article->author_id === currentUserId(),
)->addTransition(
    ArticleState::Published, ArticleEvent::Archive, ArticleState::Archived,
);

$sm = new \Rokde\StateMachine\StateMachine($articleRegistry);
$nextStatus = $sm->apply($article->status, ArticleEvent::Submit, $article);
$article->status = $nextStatus;
$article->save();

$transformer = new Rokde\StateMachine\Transformers\RegistryMermaidTransformer();
$mermaidCode = $transformer->transform($articleRegistry);