# Actions
Actions are single-purpose service classes that runs a specific task. You can think of them as service classes that runs business logic, like:
- Creating resources
- Dispatching events
- Sending webhook requests
- etc
# Methods
All action classes must have only one public method - execute(). Arguments of this method depends on action's use case.
Other than execute() method action classes can also have constructor method.
But constructor method should only be used for dependency injection from application container.
# Naming convention
Generally actions are named by the action they run and always have Action suffix.
This is to avoid possible naming collisions with other similarly named classes and also make them easily detectable as action classes.
# Usage
Generally, action classes must be always invoked from application container and not instantiated manually.
// Bad
class PostsController
{
public function publish()
{
$publishPostAction = new PublishPostAction();
}
}
// Good
class PostsController
{
public function publish(PublishPostAction $publishPostAction)
{
//
}
}
The only exception to this rule is usage of action classes in test classes. There, if action class does not have any dependencies on the constructor, it is fine to instantiate them manually.
public function testActionClass(): void
{
// OK
(new PublishPosAction())->execute($post);
// alternatively you can also request container to give you instantiated class
$this->app(PublishPosAction::class)->execute($post);
// If action class has constructor dependency you must always use container to get instantiated class
// Bad
(new PublishPosAction($someDependency))->execute($post);
// Good
$this->app(PublishPosAction::class)->execute($post);
}