Skip to main content

Overview

Actions encapsulate business logic that can be reused throughout your application. You can replace core actions with your own custom implementations to modify behavior.

Replacing a Core Action

To replace a core action, bind the action contract to your custom implementation in a service provider:
<?php

namespace App\Providers;

use App\Actions\CreateOrderAction;
use Esign\UnleashCommerce\Core\Contracts\Actions\Orders\CreateOrderAction as CreateOrderActionContract;
use Illuminate\Support\ServiceProvider;

class UnleashCommerceServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->registerActions();
    }

    protected function registerActions(): void
    {
        $this->app->bind(
            CreateOrderActionContract::class,
            CreateOrderAction::class
        );
    }
}
Your custom action should implement the same interface as the core action:
namespace App\Actions;

use Esign\UnleashCommerce\Core\Contracts\Actions\Orders\CreateOrderAction as CreateOrderActionContract;
use Esign\UnleashCommerce\Core\Models\Order;

class CreateOrderAction implements CreateOrderActionContract
{
    public function execute(array $data): Order
    {
        // Your custom implementation
        $order = Order::create($data);
        
        // Add custom behavior
        $this->notifyWarehouse($order);
        
        return $order;
    }

    private function notifyWarehouse(Order $order): void
    {
        // Custom logic
    }
}

Using Actions

Actions are resolved from the container and can be injected directly:
namespace App\Http\Controllers;

use Esign\UnleashCommerce\Core\Contracts\Actions\Orders\CreateOrderAction;

class OrderController extends Controller
{
    public function store(CreateOrderAction $createOrder)
    {
        $order = $createOrder->execute($this->validated());
        
        return response()->json($order);
    }
}

Testing Actions

Test your custom actions in isolation:
public function test_creates_order_and_notifies_warehouse()
{
    // Arrange
    $data = [
        'customer_id' => Customer::factory()->create()->getKey(),
        'total' => 100.00,
    ];

    // Act
    $action = $this->app->make(CreateOrderAction::class);
    $order = $action->execute($data);

    // Assert
    $this->assertDatabaseHas(Order::class, [
        'customer_id' => $data['customer_id'],
        'total' => $data['total'],
    ]);
}

Available core actions

See the Actions Reference for a complete list of available actions you can replace.