The Safemood/laravel-workflow
package deal by Khalil Bouzidi simplifies workflows in Laravel with clear motion definitions and occasion monitoring. With this package deal, you’ll be able to outline advanced workflows, break them up into actions, and outline occasions.
At a excessive stage, this package deal defines Workflow
courses, which include a number of Motion
courses. You possibly can create actions and workflows utilizing the package deal’s supplied command:
php artisan make:workflow PaymentWorkflow
php artisan make:motion ValidateCartItems
The challenge’s readme has this instance for a ValidateCartItems
motion:
namespace AppActions;
use SafemoodWorkflowAction;
class ValidateCartItems extends Motion
{
public perform deal with(array &$context)
{
// Simulate further validation logic
if (empty($context['cart'])) {
throw new Exception('Cart is empty');
}
// you'll be able to go knowledge to the subsequent motion if you'd like
$context['validated'] = true;
}
}
Within the workflow’s deal with()
technique, you’ll be able to outline earlier than, essential, and “after” actions and observe occasions. Right here’s an instance PaymentWorkflow deal with
technique from the package deal’s readme:
public perform deal with()
{
// Actions to be executed earlier than the principle motion
$this->addBeforeActions([
new ValidateCartItems(),
new CalculateTotal()
]);
// The principle motion of the workflow
$this->addMainAction(new MakePayment());
// Actions to be executed after the principle motion
$this->addAfterAction(new SendEmails()); // Regular laravel Job on this instance
// Observers to register for particular entities
$this->registerObservers([
Order::class => OrderObserver::class,
]);
$this->trackEvents([
PaymentProcessed::class
]);
}
Lastly, you’ll be able to run the workflow and assert the outcomes from the workflow:
$context = [
'cart' => [
['id' => 1, 'name' => 'Product A', 'price' => 100, 'quantity' => 2],
['id' => 2, 'name' => 'Product B', 'price' => 50, 'quantity' => 1]
],
'user_id' => 123
];
// Execute the PaymentWorkflow with the supplied context
$paymentWorkflow = (new PaymentWorkflow)->run($context);
// Test if the workflow execution was profitable
$success = $paymentWorkflow->passes();
// Test if the workflow execution failed
$failure = $paymentWorkflow->failed();
You possibly can study extra about this package deal, get full set up directions, and examine the supply code on GitHub. You possibly can set up this package deal through Composer for Laravel v10 and v11 utilizing the next command:
composer require safemood/laravel-workflow