PHP code example of bvtterfly / model-state-machine
1. Go to this page and download the library: Download bvtterfly/model-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/ */
bvtterfly / model-state-machine example snippets
use Bvtterfly\ModelStateMachine\Attributes\AllowTransitionTo;
use Bvtterfly\ModelStateMachine\Attributes\InitialState;
enum PostState: string
{
#[InitialState]
#[AllowTransitionTo(self::PENDING)]
case DRAFT = 'draft';
#[AllowTransitionTo(self::PUBLISHED)]
case PENDING = 'pending';
case PUBLISHED = 'published';
}
class Post extends Model
{
use HasStateMachine;
protected $casts = [
'status' => PostState::class
];
public function getStateMachineFields(): array
{
return [
'status'
];
}
}
$stateMachine = $post->getStateMachine('status')
$stateMachine->getAllStates();
$stateMachine->getStateTransitions();
$stateMachine->getStateTransitions(PostState::PENDING);
// or $stateMachine->getStateTransitions('pending');
$stateMachine->transitionTo(PostState::PUBLISHED);
// or $stateMachine->transitionTo('published');
enum PostState: string
{
#[InitialState]
#[AllowTransitionTo(self::PENDING)]
case DRAFT = 'draft';
#[AllowTransitionTo(self::PUBLISHED)]
case PENDING = 'pending';
#[Actions(SendTweetAction::class, SendEmailToSubscribers::class)]
case PUBLISHED = 'published';
}
class SendTweetAction implements StateMachineAction
{
public function handle(Model $model, array $additionalData): void
{
// send tweet...
}
}
enum PostState: string
{
#[InitialState]
#[AllowTransitionTo(self::PENDING, [SendNotificationToAdmin::class])]
case DRAFT = 'draft';
#[AllowTransitionTo(self::PUBLISHED)]
case PENDING = 'pending';
#[Actions(SendTweetAction::class, SendEmailToSubscribers::class)]
case PUBLISHED = 'published';
}