#[injectable] macro provides automatic dependency injection and singleton registration.
Generating Actions
The fastest way to create a new action is using the Kit CLI:- Create
src/actions/create_user.rswith an action stub - Update
src/actions/mod.rsto export the new action
Action Structure
Actions are structs marked with#[injectable] that contain business logic:
The #[injectable] Macro
The #[injectable] macro provides powerful dependency injection:
- Automatic registration: Actions are automatically registered as singletons in the container
- Zero boilerplate: No manual container configuration required
- Compile-time safety: Type-safe dependency resolution
Using Actions in Controllers
Resolve actions from the container usingApp::resolve():
? operator handles the case where the action isn’t registered, returning an appropriate error response.
Async Actions
Actions can be async for database operations and other I/O tasks:Actions with Dependencies
Actions can have dependencies injected via the#[inject] attribute:
When to Use Actions
Actions are ideal for:| Use Case | Example |
|---|---|
| Business operations | CreateOrderAction, ProcessPaymentAction |
| Data transformations | CalculateTotalsAction, GenerateReportAction |
| External integrations | SendEmailAction, SyncInventoryAction |
| Complex queries | SearchProductsAction, GetDashboardStatsAction |
| Multi-step processes | RegisterUserAction, CheckoutAction |
Actions vs Controllers
| Controllers | Actions |
|---|---|
| Handle HTTP requests | Contain business logic |
| Route-specific | Reusable across routes |
| Thin and focused | Rich domain logic |
| Call actions | Called by controllers |
File Organization
The standard file structure for actions:Practical Examples
User Registration Action
Action with Return Types
Using Multiple Actions in a Controller
Summary
| Feature | Usage |
|---|---|
| Generate action | kit make:action Name |
| Make injectable | #[injectable] on struct |
| Inject dependency | #[inject] on field |
| Resolve action | App::resolve::<ActionType>()? |
| Sync execute | action.execute() |
| Async execute | action.execute().await? |
| File location | src/actions/ |