@@ -16,6 +16,7 @@ Laravel Workflow combines feature details into one class, allowing for action de
16
16
- [ Define Workflow Logic] ( #define-workflow-logic )
17
17
- [ Execute Workflow] ( #execute-workflow )
18
18
- [ Conditional Action Execution] ( #conditional-action-execution )
19
+ - [ Using DTO for Context] ( #using-dto-for-context )
19
20
20
21
## Installation
21
22
@@ -47,18 +48,19 @@ php artisan make:workflow-action ValidateCartItems
47
48
namespace App\Actions;
48
49
49
50
use Safemood\Workflow\Action;
51
+ use App\DTO\CartDTO;
50
52
51
53
class ValidateCartItems extends Action
52
54
{
53
- public function handle(array & $context)
55
+ public function handle(CartDTO & $context)
54
56
{
55
57
// Simulate extra validation logic
56
- if (empty($context[' cart'] )) {
58
+ if (empty($context-> cart)) {
57
59
throw new \Exception('Cart is empty');
58
60
}
59
61
60
62
// you can pass data to the next action if you want
61
- $context[' validated'] = true;
63
+ $context-> validated = true;
62
64
63
65
}
64
66
}
@@ -132,19 +134,20 @@ namespace App\Http\Controllers;
132
134
133
135
use App\Workflows\PaymentWorkflow;
134
136
use Illuminate\Http\Request;
137
+ use App\DTO\CartDTO;
135
138
136
139
class PaymentController extends Controller
137
140
{
138
141
public function payment(Request $request)
139
142
{
140
- // Example context data representing a user's cart and user information
141
- $context = [
142
- 'cart' => [
143
+ // Example context data representing a user's cart and user information
144
+ $context = new CartDTO(
145
+ [
143
146
['id' => 1, 'name' => 'Product A', 'price' => 100, 'quantity' => 2],
144
147
['id' => 2, 'name' => 'Product B', 'price' => 50, 'quantity' => 1]
145
148
],
146
- 'user_id' => 123
147
- ] ;
149
+ 123
150
+ ) ;
148
151
149
152
// Execute the PaymentWorkflow with the provided context
150
153
$paymentWorkflow = (new PaymentWorkflow)->run($context);
@@ -214,3 +217,26 @@ class PaymentWorkflow extends WorkflowManager
214
217
}
215
218
}
216
219
```
220
+
221
+ ## Using DTO for Context
222
+
223
+ DTOInterface and BaseDTO allow you to handle context type-safely by using DTOs instead of raw arrays. Here's an example of defining a CartDTO class:
224
+
225
+ ``` php
226
+ <?php
227
+
228
+ namespace App\DTO;
229
+
230
+ use Safemood\Workflow\DTO\BaseDTO;
231
+
232
+ class CartDTO extends BaseDTO
233
+ {
234
+ public function __construct(
235
+ public array $cart,
236
+ public int $user_id,
237
+ public bool $validated = false
238
+ ) {}
239
+ // BaseDTO already implements the DTOInterface
240
+ // Automatically generates getter, setter, and toArray() methods
241
+ }
242
+ ```
0 commit comments