PHP code example of dereuromark / cakephp-workflow
1. Go to this page and download the library: Download dereuromark/cakephp-workflow 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/ */
namespace App\Workflow\Order;
use Workflow\Attribute\StateMachine;
use Workflow\State\AbstractState;
#[StateMachine(name: 'order', table: 'Orders', field: 'state')]
abstract class OrderState extends AbstractState
{
}
namespace App\Workflow\Order;
use Workflow\Attribute\Command;
use Workflow\Attribute\FinalState;
use Workflow\Attribute\Guard;
use Workflow\Attribute\InitialState;
use Workflow\Attribute\Transition;
#[InitialState]
#[Transition(to: PaidState::class, name: 'pay', happy: true)]
class PendingState extends OrderState
{
#[Guard('pay')]
public function ensurePayable(): bool|string
{
return (float)$this->getEntity()?->get('total') > 0
? true
: 'Order total must be positive';
}
#[Command('pay')]
public function markPaymentCaptured(): void
{
$this->getEntity()?->set('payment_captured', true);
}
}
namespace App\Workflow\Order;
use Workflow\Attribute\FinalState;
use Workflow\Attribute\OnEnter;
#[FinalState]
class PaidState extends OrderState
{
#[OnEnter]
public function sendReceipt(): void
{
// Runs after the entity enters the paid state.
}
}
public function initialize(array $config): void
{
$this->addBehavior('Workflow.Workflow', [
'workflow' => 'order',
]);
}
$behavior = $this->Orders->getBehavior('Workflow');
if ($behavior->canTransition($order, 'pay')) {
// Atomic: applies transition, saves entity, logs - all in one transaction
$result = $behavior->transition($order, 'pay', ['user_id' => $userId]);
}