PHP code example of sebdesign / laravel-state-machine
1. Go to this page and download the library: Download sebdesign/laravel-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/ */
sebdesign / laravel-state-machine example snippets
'callbacks' => [
// will be called when testing a transition
'guard' => [
'guard_on_submitting' => [
// call the callback on a specific transition
'on' => 'submit_changes',
// will call the method of this class
'do' => ['MyService', 'handle'],
// arguments for the callback
'args' => ['object'],
],
],
],
use App\User;
use App\Article;
Gate::define('approve', function (User $user, Article $article) {
//
});
'callbacks' => [
'guard' => [
'guard_on_approving' => [
// call the gate on a specific transition
'on' => 'approve',
// will call Gate:allows('approve', $article)
'can' => 'approve',
],
],
],
namespace App\Policies;
use App\User;
use App\Article;
class ArticlePolicy
{
public function approve(User $user, Article $article)
{
//
}
}
'callbacks' => [
'guard' => [
'guard_on_approving' => [
// call the policy on a specific transition
'on' => 'approve',
// will call Gate:allows('approve', $article)
'can' => 'approve',
],
],
],
// Reject the transition of the approval date is past
Event::listen(SMEvents::TEST_TRANSITION, function (TransitionEvent $event) {
$context = $event->getContext();
if ($context['approved_at']->isPast()) {
$event->setRejected();
}
});
// Check if a approve transition can be applied on some date
$stateMachine->can('approve', ['approved_at' => now()]);
// Setup an callback after publishing
[
'callbacks' => [
'after' => [
'after_publishing' => [
'on' => 'publish',
'do' => [App\Actions\PublishArticleAction::class, 'execute'],
'args' => ['object', 'event'],
],
],
],
];
// Save the publish date in your action
class PublishArticleAction
{
public function execute(Article $article, TransitionEvent $event)
{
$context = $event->getContext();
$article->update(['published_at' => $context['published_at']]);
}
}
// Apply a publish transition on some date
$stateMachine->apply('publish', false, ['published_at' => now()]);
php
// Get the article
$article = App\Article::find($id);
// Get the state machine for this article, and graph called "simple"
// Using the facade
$stateMachine = StateMachine::get($article, 'simple');
// Or using the service container with dependency injection
public function method(SM\Factory\FactoryInterface $factory)
{
$stateMachine = $factory->get($article, 'simple');
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.