<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ratheepan Jayakkumar on Medium]]></title>
        <description><![CDATA[Stories by Ratheepan Jayakkumar on Medium]]></description>
        <link>https://medium.com/@ratheepan?source=rss-62572c9122b1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*tUrMCXSDMFQ9QwGG.jpg</url>
            <title>Stories by Ratheepan Jayakkumar on Medium</title>
            <link>https://medium.com/@ratheepan?source=rss-62572c9122b1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:04:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ratheepan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Clean Service-Action Architecture: A Battle-Tested Pattern for Laravel Applications]]></title>
            <link>https://ratheepan.medium.com/clean-service-action-architecture-a-battle-tested-pattern-for-laravel-applications-dc311ecc5c29?source=rss-62572c9122b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc311ecc5c29</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Ratheepan Jayakkumar]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 17:08:06 GMT</pubDate>
            <atom:updated>2025-10-27T17:08:06.011Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Have you ever inherited a Laravel project where a single controller method spans 200+ lines? Where business logic is scattered across models, controllers, and random helper classes? Where adding a simple feature requires touching 10+ files and hoping nothing breaks?</p><p><strong>You’re not alone. </strong>This is the reality of many Laravel applications that started simple but grew without architectural guidance.</p><p>After implementing this Clean Service-Action architecture pattern across multiple Laravel applications from startups handling thousands of requests to enterprise systems processing millions, I’ve discovered it to be one of the most effective approaches for building maintainable, testable, and scalable applications.</p><p>This architecture isn’t theoretical. It’s battle-tested in production environments, handling complex business workflows, integrating with external APIs, and evolving with changing requirements while maintaining code quality and developer sanity.</p><h4>What You’ll Learn</h4><p>In this comprehensive guide, you’ll discover:</p><ul><li><strong>A clear architectural pattern</strong> that scales from prototype to enterprise</li><li><strong>Complete code examples</strong> you can copy and adapt to your projects</li><li><strong>The reasoning behind each design decision</strong> (not just what, but why)</li><li><strong>Production-ready patterns</strong> for error handling, testing</li></ul><h4>What Makes This Different</h4><p>Unlike academic architectural discussions, this article focuses on <strong>practical implementation</strong> with:</p><ul><li><strong>Generic, reusable examples</strong> (not domain-specific code)</li><li><strong>Real exception handling patterns</strong> used in production</li><li><strong>Performance considerations</strong> learned from high-traffic applications</li></ul><p>Let’s dive into building Laravel applications the right way.</p><h3>The Clean Service-Action Architecture Overview</h3><figure><img alt="Architecture Diagram" src="https://cdn-images-1.medium.com/max/965/1*PNi-0kwHwC6B0FX-xsX_ag.png" /><figcaption><strong>Architecture Diagram</strong></figcaption></figure><h4>Core Architectural Principles</h4><p>Before diving into each layer, it’s crucial to understand the <strong>strict separation of concerns</strong> that makes this Clean Service-Action architecture effective:</p><p><strong>What Controllers Must NEVER Do:</strong></p><ul><li>Call Actions directly</li><li>Access Repositories directly</li><li>Contain business logic</li><li>Handle database operations</li><li>Perform complex data transformations</li></ul><p><strong>Proper Layer Communication:</strong></p><pre>// ✅ CORRECT: Controller → Service → Action → Repository → Model<br>class ProductController <br>{<br>    public function store(CreateProductRequest $request)<br>    {<br>        $data = CreateProductData::from($request-&gt;validated());<br>        $product = $this-&gt;productService-&gt;createProduct($data); // ← Service only!<br>        return new ProductResource($product);<br>    }<br>}</pre><pre>// ❌ WRONG: Controller directly calling Action<br>class ProductController <br>{<br>    public function store(CreateProductRequest $request)<br>    {<br>        $data = CreateProductData::from($request-&gt;validated());<br>        $product = $this-&gt;createProductAction-&gt;execute($data); // ← Never do this!<br>        return new ProductResource($product);<br>    }<br>}</pre><h4>Why This Matters</h4><ul><li><strong>Maintainability:</strong> Each layer has a single, clear responsibility</li><li><strong>Testability:</strong> You can mock Services without knowing about Actions</li><li><strong>Flexibility:</strong> Services can orchestrate multiple Actions as business logic evolves</li><li><strong>Consistency:</strong> All business workflows go through the same entry point (Services)</li></ul><h3>Layer 1: Controllers — The HTTP Gateway</h3><h4>Purpose &amp; Responsibilities</h4><ul><li>HTTP Request/Response handling</li><li>Input validation (via Form Requests)</li><li>Response formatting** (via API Resources)</li><li>Exception handling</li><li>Authentication/Authorization</li></ul><h4>Advantages</h4><ul><li>Thin controllers — No business logic pollution</li><li>Consistent API responses</li><li>Centralized validation</li><li>Easy testing — Mock services for unit tests</li></ul><h4>Generic Example</h4><pre>&lt;?php<br><br>namespace App\Http\Controllers\Api;<br><br>use App\Http\Controllers\Controller;<br>use App\Http\Requests\Product\CreateProductRequest;<br>use App\Http\Requests\Product\UpdateProductRequest;<br>use App\Http\Resources\Product\ProductResource;<br>use App\Contracts\Services\ProductServiceInterface;<br>use App\DTOs\Product\CreateProductData;<br>use App\DTOs\Product\UpdateProductData;<br>use App\Exceptions\{BusinessRuleException, ProductException, ExternalServiceException, ResponseHttpException};<br>use App\Enum\{ErrorCode, ErrorMessage};<br>use Illuminate\Http\Request;<br>use Illuminate\Support\Facades\Log;<br>use Symfony\Component\HttpFoundation\Response;<br>use Exception;<br><br>class ProductController extends Controller<br>{<br>    public function __construct(<br>        private readonly ProductServiceInterface $productService<br>    ) {}<br><br>    /**<br>     * Display a listing of products<br>     */<br>    public function index(Request $request)<br>    {<br>        $products = $this-&gt;productService-&gt;getAllProducts(<br>            page: (int) $request-&gt;input(&#39;page&#39;, 1),<br>            perPage: (int) $request-&gt;input(&#39;per_page&#39;, 15),<br>            search: $request-&gt;input(&#39;search&#39;),<br>            category: $request-&gt;input(&#39;category&#39;),<br>            status: $request-&gt;input(&#39;status&#39;)<br>        );<br><br>        return ProductResource::collection($products);<br>    }<br><br>    /**<br>     * Store a new product<br>     */<br>    public function store(CreateProductRequest $request)<br>    {<br>        try {<br>            $productData = CreateProductData::from($request-&gt;validated());<br>            $product = $this-&gt;productService-&gt;createProduct($productData);<br>            <br>            return (new ProductResource($product))<br>                -&gt;response()<br>                -&gt;setStatusCode(Response::HTTP_CREATED);<br>        } catch (BusinessRuleException $e) {<br>            throw new ResponseHttpException(<br>                ErrorCode::BusinessRuleViolation,<br>                $e-&gt;getMessage(),<br>                Response::HTTP_UNPROCESSABLE_ENTITY<br>            );<br>        } catch (ProductException $e) {<br>            throw new ResponseHttpException(<br>                $e-&gt;getErrorCode(),<br>                $e-&gt;getErrorMessage(),<br>                Response::HTTP_BAD_REQUEST<br>            );<br>        } catch (ExternalServiceException $e) {<br>            throw new ResponseHttpException(<br>                $e-&gt;getErrorCode(),<br>                $e-&gt;getErrorMessage(),<br>                Response::HTTP_SERVICE_UNAVAILABLE<br>            );<br>        } catch (Exception $e) {<br>            Log::error(&#39;Unexpected error during product creation&#39;, [<br>                &#39;error&#39; =&gt; $e-&gt;getMessage(),<br>                &#39;trace&#39; =&gt; $e-&gt;getTraceAsString(),<br>                &#39;request_data&#39; =&gt; $request-&gt;validated()<br>            ]);<br>            <br>            throw new ResponseHttpException(<br>                ErrorCode::CreationFailed,<br>                ErrorMessage::CreationFailed,<br>                Response::HTTP_INTERNAL_SERVER_ERROR<br>            );<br>        }<br>    }<br><br>    /**<br>     * Display specific product<br>     */<br>    public function show(string $uuid)<br>    {<br>        try {<br>            $product = $this-&gt;productService-&gt;findProductByUuid($uuid);<br>            <br>            if (!$product) {<br>                throw new ResponseHttpException(<br>                    ErrorCode::NotFound,<br>                    ErrorMessage::NotFound,<br>                    Response::HTTP_NOT_FOUND<br>                );<br>            }<br><br>            return new ProductResource($product);<br>        } catch (ProductException $e) {<br>            throw new ResponseHttpException(<br>                $e-&gt;getErrorCode(),<br>                $e-&gt;getErrorMessage(),<br>                Response::HTTP_BAD_REQUEST<br>            );<br>        } catch (ExternalServiceException $e) {<br>            throw new ResponseHttpException(<br>                $e-&gt;getErrorCode(),<br>                $e-&gt;getErrorMessage(),<br>                Response::HTTP_SERVICE_UNAVAILABLE<br>            );<br>        } catch (Exception $e) {<br>            Log::error(&#39;Error retrieving product&#39;, [<br>                &#39;uuid&#39; =&gt; $uuid,<br>                &#39;error&#39; =&gt; $e-&gt;getMessage()<br>            ]);<br>            <br>            throw new ResponseHttpException(<br>                ErrorCode::InternalServerError,<br>                ErrorMessage::InternalServerError,<br>                Response::HTTP_INTERNAL_SERVER_ERROR<br>            );<br>        }<br>    }<br><br>    /**<br>     * Update product<br>     */<br>    public function update(UpdateProductRequest $request, string $uuid)<br>    {<br>        try {<br>            $productData = UpdateProductData::from($request-&gt;validated());<br>            $product = $this-&gt;productService-&gt;updateProduct($uuid, $productData);<br>            <br>            return new ProductResource($product);<br>        } catch (BusinessRuleException $e) {<br>            throw new ResponseHttpException(<br>                $e-&gt;getErrorCode(),<br>                $e-&gt;getErrorMessage(),<br>                Response::HTTP_UNPROCESSABLE_ENTITY<br>            );<br>        } catch (ProductException $e) {<br>            throw new ResponseHttpException(<br>                $e-&gt;getErrorCode(),<br>                $e-&gt;getErrorMessage(),<br>                Response::HTTP_BAD_REQUEST<br>            );<br>        } catch (ExternalServiceException $e) {<br>            throw new ResponseHttpException(<br>                $e-&gt;getErrorCode(),<br>                $e-&gt;getErrorMessage(),<br>                Response::HTTP_SERVICE_UNAVAILABLE<br>            );<br>        } catch (Exception $e) {<br>            Log::error(&#39;Error updating product&#39;, [<br>                &#39;uuid&#39; =&gt; $uuid,<br>                &#39;error&#39; =&gt; $e-&gt;getMessage()<br>            ]);<br>            <br>            throw new ResponseHttpException(<br>                ErrorCode::InternalServerError,<br>                ErrorMessage::InternalServerError,<br>                Response::HTTP_INTERNAL_SERVER_ERROR<br>            );<br>        }<br>    }<br><br>    /**<br>     * Delete product<br>     */<br>    public function destroy(string $uuid)<br>    {<br>        try {<br>            $this-&gt;productService-&gt;deleteProduct($uuid);<br>            <br>            return response()-&gt;json([<br>                &#39;message&#39; =&gt; &#39;Product deleted successfully&#39;<br>            ]);<br>        } catch (BusinessRuleException $e) {<br>            throw new ResponseHttpException(<br>                $e-&gt;getErrorCode(),<br>                $e-&gt;getErrorMessage(),<br>                Response::HTTP_UNPROCESSABLE_ENTITY<br>            );<br>        } catch (ProductException $e) {<br>            throw new ResponseHttpException(<br>                $e-&gt;getErrorCode(),<br>                $e-&gt;getErrorMessage(),<br>                Response::HTTP_BAD_REQUEST<br>            );<br>        } catch (ExternalServiceException $e) {<br>            throw new ResponseHttpException(<br>                $e-&gt;getErrorCode(),<br>                $e-&gt;getErrorMessage(),<br>                Response::HTTP_SERVICE_UNAVAILABLE<br>            );<br>        } catch (Exception $e) {<br>            Log::error(&#39;Error deleting product&#39;, [<br>                &#39;uuid&#39; =&gt; $uuid,<br>                &#39;error&#39; =&gt; $e-&gt;getMessage()<br>            ]);<br>            <br>            throw new ResponseHttpException(<br>                ErrorCode::InternalServerError,<br>                ErrorMessage::InternalServerError,<br>                Response::HTTP_INTERNAL_SERVER_ERROR<br>            );<br>        }<br>    }<br>}</pre><h4>Key Implementation Notes</h4><ul><li><strong>Dependency Injection</strong>: Service injected via constructor</li><li><strong>DTO Conversion:</strong> Request data converted to DTOs</li><li><strong>Resource Responses:</strong> Consistent API formatting</li><li><strong>HTTP Status Codes:</strong> Proper REST compliance</li><li><strong>Exception Handling: </strong>Comprehensive try-catch blocks with specific error responses</li><li><strong>Error Logging: </strong>Detailed logging for debugging and monitoring</li><li><strong>Consistent Error Format:</strong> Standardized error response structure</li></ul><h3>Layer 2: Services — The Workflow Orchestrators</h3><h4>Purpose &amp; Responsibilities</h4><ul><li>Business workflow orchestration</li><li>Multiple Action coordination</li><li>Cross-cutting concerns (caching, logging)</li><li>Complex business rules</li><li>Transaction management</li></ul><h4>Advantages</h4><ul><li>Single entry point for business workflows</li><li>Reusable business logic</li><li>Transaction boundaries</li><li>Easy mocking in tests</li><li>Centralized caching and logging</li></ul><h4>Generic Example</h4><pre>&lt;?php<br><br>namespace App\Services;<br><br>use App\Contracts\Services\ProductServiceInterface;<br>use App\Contracts\Repositories\ProductRepositoryInterface;<br>use App\Actions\Product\{<br>    CreateProduct,<br>    UpdateProduct,<br>    DeleteProduct,<br>    ListProducts,<br>    GetProductByUuid,<br>    ValidateProductData<br>};<br>use App\DTOs\Product\{CreateProductData, UpdateProductData, ProductData};<br>use App\Exceptions\{BusinessRuleException, ProductException};<br>use App\Enum\{ErrorCode, ErrorMessage};<br>use Illuminate\Database\QueryException;<br>use Illuminate\Pagination\LengthAwarePaginator;<br>use Illuminate\Support\Facades\{DB, Cache, Log};<br>use Exception;<br><br>class ProductService implements ProductServiceInterface<br>{<br>    public function __construct(<br>        private readonly CreateProduct $createProduct,<br>        private readonly UpdateProduct $updateProduct,<br>        private readonly DeleteProduct $deleteProduct,<br>        private readonly ListProducts $listProducts,<br>        private readonly GetProductByUuid $getProductByUuid,<br>        private readonly ValidateProductData $validateProductData<br>    ) {}<br><br>    /**<br>     * Get paginated list of products<br>     */<br>    public function getAllProducts(<br>        int $page = 1,<br>        int $perPage = 15,<br>        ?string $search = null,<br>        ?string $category = null,<br>        ?string $status = null<br>    ): LengthAwarePaginator {<br>        try {<br>            $cacheKey = &quot;products.list.{$page}.{$perPage}.&quot; . md5($search . $category . $status);<br>            <br>            return Cache::tags([&#39;products&#39;])-&gt;remember($cacheKey, 300, function () use (<br>                $page, $perPage, $search, $category, $status<br>            ) {<br>                return $this-&gt;listProducts-&gt;execute($page, $perPage, $search, $category, $status);<br>            });<br>        } catch (Exception $e) {<br>            Log::error(&#39;Error fetching products list&#39;, [<br>                &#39;page&#39; =&gt; $page,<br>                &#39;perPage&#39; =&gt; $perPage,<br>                &#39;search&#39; =&gt; $search,<br>                &#39;error&#39; =&gt; $e-&gt;getMessage()<br>            ]);<br>            <br>            throw new ProductException(<br>                ErrorCode::InternalServerError,<br>                ErrorMessage::InternalServerError<br>            );<br>        }<br>    }<br><br>    /**<br>     * Create new product with validation and business rules<br>     */<br>    public function createProduct(CreateProductData $data): ProductData<br>    {<br>        return DB::transaction(function () use ($data) {<br>            // Validate business rules<br>            $this-&gt;validateProductData-&gt;execute($data);<br>            <br>            // Create the product<br>            $product = $this-&gt;createProduct-&gt;execute($data);<br>            <br>            // Clear related caches<br>            Cache::tags([&#39;products&#39;, &#39;categories&#39;])-&gt;flush();<br>            <br>            // Log activity<br>            Log::info(&#39;Product created&#39;, [&#39;product_id&#39; =&gt; $product-&gt;id, &#39;name&#39; =&gt; $product-&gt;name]);<br>            <br>            return $product;<br>        });<br>    }<br><br>    /**<br>     * Find product by UUID<br>     */<br>    public function findProductByUuid(string $uuid): ?ProductData<br>    {<br>        try {<br>            $cacheKey = &quot;product.uuid.{$uuid}&quot;;<br>            <br>            return Cache::tags([&#39;products&#39;])-&gt;remember($cacheKey, 600, function () use ($uuid) {<br>                return $this-&gt;getProductByUuid-&gt;execute($uuid);<br>            });<br>        } catch (Exception $e) {<br>            Log::error(&#39;Error finding product by UUID&#39;, [<br>                &#39;uuid&#39; =&gt; $uuid,<br>                &#39;error&#39; =&gt; $e-&gt;getMessage()<br>            ]);<br>            <br>            throw new ProductException(<br>                ErrorCode::InternalServerError,<br>                ErrorMessage::InternalServerError<br>            );<br>        }<br>    }<br><br>    /**<br>     * Update product with business validation<br>     */<br>    public function updateProduct(string $uuid, UpdateProductData $data): ProductData<br>    {<br>        return DB::transaction(function () use ($uuid, $data) {<br>            try {<br>                // Get existing product<br>                $existingProduct = $this-&gt;findProductByUuid($uuid);<br>                if (!$existingProduct) {<br>                    throw new ProductException(<br>                        ErrorCode::NotFound,<br>                        ErrorMessage::NotFound<br>                    );<br>                }<br><br>                // Validate business rules<br>                $this-&gt;validateProductData-&gt;execute($data, $existingProduct);<br>                <br>                // Update the product<br>                $product = $this-&gt;updateProduct-&gt;execute($uuid, $data);<br>                <br>                // Clear caches<br>                Cache::tags([&#39;products&#39;])-&gt;flush();<br>                Cache::forget(&quot;product.uuid.{$uuid}&quot;);<br>                <br>                Log::info(&#39;Product updated&#39;, [&#39;product_id&#39; =&gt; $product-&gt;id]);<br>                <br>                return $product;<br>            } catch (BusinessRuleException $e) {<br>                // Business rule violations - let them bubble up<br>                throw $e;<br>            } catch (ProductException $e) {<br>                // Product-specific exceptions - let them bubble up<br>                throw $e;<br>            } catch (QueryException $e) {<br>                Log::error(&#39;Database error during product update&#39;, [<br>                    &#39;uuid&#39; =&gt; $uuid,<br>                    &#39;error&#39; =&gt; $e-&gt;getMessage(),<br>                    &#39;data&#39; =&gt; $data-&gt;toArray()<br>                ]);<br>                <br>                throw new ProductException(<br>                    ErrorCode::DatabaseError,<br>                    ErrorMessage::DatabaseError<br>                );<br>            } catch (Exception $e) {<br>                Log::error(&#39;Unexpected error during product update&#39;, [<br>                    &#39;uuid&#39; =&gt; $uuid,<br>                    &#39;error&#39; =&gt; $e-&gt;getMessage(),<br>                    &#39;service&#39; =&gt; static::class,<br>                    &#39;method&#39; =&gt; &#39;updateProduct&#39;<br>                ]);<br>                <br>                throw new ProductException(<br>                    ErrorCode::InternalServerError,<br>                    ErrorMessage::InternalServerError<br>                );<br>            }<br>        });<br>    }<br><br>    /**<br>     * Delete product with cleanup<br>     */<br>    public function deleteProduct(string $uuid): void<br>    {<br>        DB::transaction(function () use ($uuid) {<br>            try {<br>                // Check if product exists<br>                $existingProduct = $this-&gt;findProductByUuid($uuid);<br>                if (!$existingProduct) {<br>                    throw new ProductException(<br>                        ErrorCode::NotFound,<br>                        ErrorMessage::NotFound<br>                    );<br>                }<br>                <br>                $this-&gt;deleteProduct-&gt;execute($uuid);<br>                <br>                // Clear caches<br>                Cache::tags([&#39;products&#39;])-&gt;flush();<br>                Cache::forget(&quot;product.uuid.{$uuid}&quot;);<br>                <br>                Log::info(&#39;Product deleted&#39;, [&#39;product_uuid&#39; =&gt; $uuid]);<br>            } catch (ProductException $e) {<br>                // Product-specific exceptions - let them bubble up<br>                throw $e;<br>            } catch (QueryException $e) {<br>                Log::error(&#39;Database error during product deletion&#39;, [<br>                    &#39;uuid&#39; =&gt; $uuid,<br>                    &#39;error&#39; =&gt; $e-&gt;getMessage()<br>                ]);<br>                <br>                throw new ProductException(<br>                    ErrorCode::DatabaseError,<br>                    ErrorMessage::DatabaseError<br>                );<br>            } catch (Exception $e) {<br>                Log::error(&#39;Unexpected error during product deletion&#39;, [<br>                    &#39;uuid&#39; =&gt; $uuid,<br>                    &#39;error&#39; =&gt; $e-&gt;getMessage()<br>                ]);<br>                <br>                throw new ProductException(<br>                    ErrorCode::InternalServerError,<br>                    ErrorMessage::InternalServerError<br>                );<br>            }<br>        });<br>    }<br>}</pre><h4>Key Implementation Notes</h4><ul><li><strong>Action Orchestration:</strong> Multiple actions coordinated</li><li><strong>Transaction Management:</strong> Database consistency with automatic rollback</li><li><strong>Caching Strategy:</strong> Tagged cache invalidation</li><li><strong>Business Validation:</strong> Complex rule enforcement</li><li><strong>Exception Handling:</strong> Layer-specific error handling and propagation</li><li><strong>Error Logging:</strong> Comprehensive error tracking with context</li><li><strong>Domain Exceptions:</strong> Custom exceptions for better error categorization</li></ul><h3>Layer 3: Actions — Single-Purpose Business Logic</h3><h4>Purpose &amp; Responsibilities</h4><ul><li>Single business operation</li><li>Focused responsibility</li><li>Reusable logic units</li><li>Domain-specific operations</li></ul><h4>Advantages</h4><ul><li>Single Responsibility Principle</li><li>Easy testing — Focused scope</li><li>Reusability across services</li><li>Clear business intent</li><li>Immutable operations</li></ul><h4>Generic Example</h4><pre>&lt;?php<br><br>namespace App\Actions\Product;<br><br>use App\Contracts\Repositories\ProductRepositoryInterface;<br>use App\DTOs\Product\{CreateProductData, ProductData};<br><br>readonly class CreateProduct<br>{<br>    public function __construct(<br>        private ProductRepositoryInterface $productRepository<br>    ) {}<br><br>    /**<br>     * Create a new product<br>     */<br>    public function execute(CreateProductData $data): ProductData<br>    {<br>        return $this-&gt;productRepository-&gt;create($data);<br>    }<br>}</pre><pre>&lt;?php<br><br>namespace App\Actions\Product;<br><br>use App\Contracts\Repositories\{ProductRepositoryInterface, CategoryRepositoryInterface};<br>use App\DTOs\Product\CreateProductData;<br>use App\Exceptions\BusinessRuleException;<br><br>readonly class ValidateProductData<br>{<br>    public function __construct(<br>        private ProductRepositoryInterface $productRepository,<br>        private CategoryRepositoryInterface $categoryRepository<br>    ) {}<br><br>    /**<br>     * Validate product data against business rules<br>     */<br>    public function execute(CreateProductData $data, ?ProductData $existingProduct = null): void<br>    {<br>        // Check for duplicate SKU<br>        if ($this-&gt;productRepository-&gt;existsBySku($data-&gt;sku, $existingProduct?-&gt;id)) {<br>            throw new BusinessRuleException(&#39;Product SKU already exists&#39;);<br>        }<br><br>        // Validate category exists and is active<br>        $category = $this-&gt;categoryRepository-&gt;findById($data-&gt;categoryId);<br>        if (!$category || !$category-&gt;isActive) {<br>            throw new BusinessRuleException(&#39;Invalid or inactive category&#39;);<br>        }<br><br>        // Business rule: Price must be positive<br>        if ($data-&gt;price &lt;= 0) {<br>            throw new BusinessRuleException(&#39;Product price must be positive&#39;);<br>        }<br><br>        // Business rule: Sale price cannot exceed regular price<br>        if ($data-&gt;salePrice &amp;&amp; $data-&gt;salePrice &gt;= $data-&gt;price) {<br>            throw new BusinessRuleException(&#39;Sale price must be lower than regular price&#39;);<br>        }<br>    }<br>}</pre><h4>Key Implementation Notes</h4><ul><li><strong>Readonly Classes:</strong> Immutable state</li><li><strong>Single Method:</strong> `execute()` for consistency</li><li><strong>Focused Logic:</strong> One business operation</li><li><strong>Domain Validation:</strong> Business rule enforcement</li></ul><h4>Optional: Async Actions</h4><p>For background processing of Actions, consider the `spatie/laravel-queueable-action` package:</p><pre>composer require spatie/laravel-queueable-action</pre><p><strong>Use Cases: </strong>Bulk operations, external API calls, heavy computations, email notifications.</p><p><strong>Implementation:</strong> Services orchestrate queueable actions, maintaining the architectural pattern while enabling background processing.</p><p><strong>Ref:</strong> <a href="https://github.com/spatie/laravel-queueable-action">GitHub — spatie/laravel-queueable-action: Queueable actions in Laravel</a></p><h3>Layer 4: Repositories — Data Access Abstraction</h3><h4>Purpose &amp; Responsibilities</h4><ul><li>Data access abstraction</li><li>Query encapsulation</li><li>Multiple data storage support</li><li>Data mapping</li></ul><h4>Advantages</h4><ul><li><strong>Database agnostic</strong> — Easy to swap implementations</li><li>Testable<strong> —</strong> Mock data sources</li><li>Query reuse — Centralized data access</li><li>Performance optimization — Query optimization layer</li></ul><h4>Interface Definition</h4><pre>&lt;?php<br><br>namespace App\Contracts\Repositories;<br><br>use App\DTOs\Product\{CreateProductData, UpdateProductData, ProductData};<br>use Illuminate\Pagination\LengthAwarePaginator;<br>use Illuminate\Support\Collection;<br><br>interface ProductRepositoryInterface<br>{<br>    /**<br>     * Get paginated products with filters<br>     */<br>    public function getPaginated(<br>        int $page,<br>        int $perPage,<br>        ?string $search = null,<br>        ?string $category = null,<br>        ?string $status = null<br>    ): LengthAwarePaginator;<br><br>    /**<br>     * Create new product<br>     */<br>    public function create(CreateProductData $data): ProductData;<br><br>    /**<br>     * Find product by UUID<br>     */<br>    public function findByUuid(string $uuid): ?ProductData;<br><br>    /**<br>     * Update product by UUID<br>     */<br>    public function updateByUuid(string $uuid, UpdateProductData $data): ProductData;<br><br>    /**<br>     * Delete product by UUID<br>     */<br>    public function deleteByUuid(string $uuid): void;<br><br>    /**<br>     * Check if product exists by SKU<br>     */<br>    public function existsBySku(string $sku, ?int $excludeId = null): bool;<br><br>    /**<br>     * Get all active products<br>     * @return Collection&lt;ProductData&gt;<br>     */<br>    public function findActive(): Collection;<br><br>    /**<br>     * Find products by category<br>     */<br>    public function findByCategory(int $categoryId): Collection;<br>}</pre><h4>Implementation Example</h4><pre>&lt;?php<br><br>namespace App\Repositories\Eloquent;<br><br>use App\Contracts\Repositories\ProductRepositoryInterface;<br>use App\Models\Product;<br>use App\DTOs\Product\{CreateProductData, UpdateProductData, ProductData};<br>use Illuminate\Pagination\LengthAwarePaginator;<br>use Illuminate\Support\Collection;<br><br>class ProductRepository implements ProductRepositoryInterface<br>{<br>    /**<br>     * Get paginated products with filters<br>     */<br>    public function getPaginated(<br>        int $page,<br>        int $perPage,<br>        ?string $search = null,<br>        ?string $category = null,<br>        ?string $status = null<br>    ): LengthAwarePaginator {<br>        $query = Product::query()<br>            -&gt;with([&#39;category&#39;, &#39;media&#39;])<br>            -&gt;select([&#39;id&#39;, &#39;uuid&#39;, &#39;name&#39;, &#39;sku&#39;, &#39;price&#39;, &#39;sale_price&#39;, &#39;status&#39;, &#39;category_id&#39;]);<br><br>        // Apply search filter<br>        if ($search) {<br>            $query-&gt;where(function ($q) use ($search) {<br>                $q-&gt;where(&#39;name&#39;, &#39;LIKE&#39;, &quot;%{$search}%&quot;)<br>                  -&gt;orWhere(&#39;sku&#39;, &#39;LIKE&#39;, &quot;%{$search}%&quot;)<br>                  -&gt;orWhere(&#39;description&#39;, &#39;LIKE&#39;, &quot;%{$search}%&quot;);<br>            });<br>        }<br><br>        // Apply category filter<br>        if ($category) {<br>            $query-&gt;whereHas(&#39;category&#39;, function ($q) use ($category) {<br>                $q-&gt;where(&#39;slug&#39;, $category);<br>            });<br>        }<br><br>        // Apply status filter<br>        if ($status) {<br>            $query-&gt;where(&#39;status&#39;, $status);<br>        }<br><br>        return $query-&gt;paginate($perPage, [&#39;*&#39;], &#39;page&#39;, $page)<br>            -&gt;through(fn ($product) =&gt; ProductData::from($product));<br>    }<br><br>    /**<br>     * Create new product<br>     */<br>    public function create(CreateProductData $data): ProductData<br>    {<br>        $product = Product::create([<br>            &#39;name&#39; =&gt; $data-&gt;name,<br>            &#39;sku&#39; =&gt; $data-&gt;sku,<br>            &#39;description&#39; =&gt; $data-&gt;description,<br>            &#39;price&#39; =&gt; $data-&gt;price,<br>            &#39;sale_price&#39; =&gt; $data-&gt;salePrice,<br>            &#39;category_id&#39; =&gt; $data-&gt;categoryId,<br>            &#39;status&#39; =&gt; $data-&gt;status,<br>            &#39;meta_data&#39; =&gt; $data-&gt;metaData,<br>        ]);<br><br>        return ProductData::from($product-&gt;load(&#39;category&#39;));<br>    }<br><br>    /**<br>     * Find product by UUID<br>     */<br>    public function findByUuid(string $uuid): ?ProductData<br>    {<br>        $product = Product::with([&#39;category&#39;, &#39;media&#39;])<br>            -&gt;where(&#39;uuid&#39;, $uuid)<br>            -&gt;first();<br><br>        return $product ? ProductData::from($product) : null;<br>    }<br><br>    /**<br>     * Update product by UUID<br>     */<br>    public function updateByUuid(string $uuid, UpdateProductData $data): ProductData<br>    {<br>        $product = Product::where(&#39;uuid&#39;, $uuid)-&gt;firstOrFail();<br>        <br>        $product-&gt;update($data-&gt;toArray());<br>        <br>        return ProductData::from($product-&gt;fresh([&#39;category&#39;, &#39;media&#39;]));<br>    }<br><br>    /**<br>     * Delete product by UUID<br>     */<br>    public function deleteByUuid(string $uuid): void<br>    {<br>        Product::where(&#39;uuid&#39;, $uuid)-&gt;delete();<br>    }<br><br>    /**<br>     * Check if product exists by SKU<br>     */<br>    public function existsBySku(string $sku, ?int $excludeId = null): bool<br>    {<br>        $query = Product::where(&#39;sku&#39;, $sku);<br>        <br>        if ($excludeId) {<br>            $query-&gt;where(&#39;id&#39;, &#39;!=&#39;, $excludeId);<br>        }<br>        <br>        return $query-&gt;exists();<br>    }<br><br>    /**<br>     * @return Collection&lt;ProductData&gt;<br>     */<br>    public function findActive(): Collection<br>    {<br>        return Product::where(&#39;status&#39;, &#39;active&#39;)<br>            -&gt;get()<br>            -&gt;map(fn($product) =&gt; ProductData::from($product));<br>    }<br><br>    /**<br>     * Find products by category<br>     */<br>    public function findByCategory(int $categoryId): Collection<br>    {<br>        return Product::where(&#39;category_id&#39;, $categoryId)<br>            -&gt;where(&#39;status&#39;, &#39;active&#39;)<br>            -&gt;get()<br>            -&gt;map(fn($product) =&gt; ProductData::from($product));<br>    }<br>}</pre><h4>Key Implementation Notes</h4><ul><li><strong>Query Optimization:</strong> Eager loading, select specific columns</li><li><strong>DTO Conversion:</strong> Model to DTO transformation</li><li><strong>Filter Handling:</strong> Dynamic query building</li><li><strong>Error Handling:</strong> Graceful failure handling</li></ul><h3>Layer 5: Models — Data Representation</h3><h4>Purpose &amp; Responsibilities</h4><ul><li>Database table representation</li><li>Relationships definition</li><li>Data casting</li><li>Model events</li></ul><h4>Advantages</h4><ul><li>Eloquent features — Rich ORM capabilities</li><li>Relationship management</li><li>Attribute casting</li><li>Model observers</li><li>Scopes and accessors</li></ul><h4>Generic Example</h4><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\{Model, Factories\HasFactory, SoftDeletes};<br>use Illuminate\Database\Eloquent\Relations\{BelongsTo, HasMany};<br>use App\Enum\ProductStatus;<br><br>class Product extends Model<br>{<br>    use HasFactory, SoftDeletes;<br><br>    protected $fillable = [<br>        &#39;name&#39;,<br>        &#39;sku&#39;,<br>        &#39;description&#39;,<br>        &#39;price&#39;,<br>        &#39;sale_price&#39;,<br>        &#39;category_id&#39;,<br>        &#39;status&#39;,<br>        &#39;meta_data&#39;,<br>    ];<br><br>    protected $casts = [<br>        &#39;price&#39; =&gt; &#39;decimal:2&#39;,<br>        &#39;sale_price&#39; =&gt; &#39;decimal:2&#39;,<br>        &#39;status&#39; =&gt; ProductStatus::class,<br>        &#39;meta_data&#39; =&gt; &#39;array&#39;,<br>    ];<br><br>    /**<br>     * Relationship: Product belongs to Category<br>     */<br>    public function category(): BelongsTo<br>    {<br>        return $this-&gt;belongsTo(Category::class);<br>    }<br><br>    /**<br>     * Relationship: Product has many Media<br>     */<br>    public function media(): HasMany<br>    {<br>        return $this-&gt;hasMany(Media::class, &#39;model_id&#39;)<br>            -&gt;where(&#39;model_type&#39;, self::class);<br>    }<br><br>    /**<br>     * Scope: Active products only<br>     */<br>    public function scopeActive($query)<br>    {<br>        return $query-&gt;where(&#39;status&#39;, ProductStatus::ACTIVE);<br>    }<br><br>    /**<br>     * Scope: Products on sale<br>     */<br>    public function scopeOnSale($query)<br>    {<br>        return $query-&gt;whereNotNull(&#39;sale_price&#39;)<br>            -&gt;where(&#39;sale_price&#39;, &#39;&gt;&#39;, 0);<br>    }<br><br>    /**<br>     * Accessor: Get effective price (sale price if available)<br>     */<br>    public function getEffectivePriceAttribute(): float<br>    {<br>        return $this-&gt;sale_price ?? $this-&gt;price;<br>    }<br>}</pre><h3>Data Transfer Objects (DTOs) — Type-Safe Data Flow</h3><h4>Purpose &amp; Responsibilities</h4><ul><li>Type-safe data transfer</li><li>Validation rules</li><li>Data transformation</li><li>API contract enforcement</li></ul><h4>Advantages</h4><ul><li>Type Safety — Compile-time error detection</li><li>Validation — Built-in data validation</li><li>Documentation — Self-documenting APIs</li><li>Transformation — Automatic data casting</li></ul><h4>Recommended Packages for Implementation</h4><p>The `spatie/laravel-data` package is the cornerstone of our DTO implementation. It provides powerful features that make DTOs both elegant and functional.</p><p><strong>Installation &amp; Setup</strong></p><pre>composer require spatie/laravel-data<br>php artisan vendor:publish --provider=&quot;Spatie\LaravelData\LaravelDataServiceProvider&quot;</pre><p><strong>Why spatie/laravel-data?</strong></p><ul><li>Automatic Validation — Built-in validation attributes</li><li>Type Casting — Automatic data type conversion</li><li>API Resource Integration — Seamless Laravel resource compatibility</li><li>Nested DTOs — Complex data structure support</li><li>Collection Handling — Easy array/collection transformation</li><li>IDE Support — Full type hinting and autocompletion</li></ul><p><strong>Ref: </strong><a href="https://spatie.be/docs/laravel-data/v4/introduction">Introduction | laravel-data | Spatie</a></p><h4>Generic Examples</h4><pre>namespace App\DTOs\Product;<br><br>use Spatie\LaravelData\Data;<br>use Spatie\LaravelData\Attributes\{<br>    Validation\Required,<br>    Validation\Max,<br>    Validation\Min,<br>    Validation\Exists,<br>    WithCast<br>};<br>use Spatie\LaravelData\Casts\EnumCast;<br>use App\Enum\ProductStatus;<br><br>class CreateProductData extends Data<br>{<br>    public function __construct(<br>        #[Required, Max(255)]<br>        public string $name,<br>        <br>        #[Required, Max(100)]<br>        public string $sku,<br>        <br>        public ?string $description,<br>        <br>        #[Required, Min(0)]<br>        public float $price,<br>        <br>        #[Min(0)]<br>        public ?float $salePrice,<br>        <br>        #[Required, Exists(&#39;categories&#39;, &#39;id&#39;)]<br>        public int $categoryId,<br>        <br>        #[WithCast(EnumCast::class, ProductStatus::class)]<br>        public ProductStatus $status = ProductStatus::ACTIVE,<br>        <br>        public ?array $metaData = null,<br>    ) {}<br>}</pre><pre>&lt;?php<br><br>namespace App\DTOs\Product;<br><br>use Spatie\LaravelData\Data;<br>use App\Enum\ProductStatus;<br>use Carbon\Carbon;<br><br>class ProductData extends Data<br>{<br>    public function __construct(<br>        public int $id,<br>        public string $uuid,<br>        public string $name,<br>        public string $sku,<br>        public ?string $description,<br>        public float $price,<br>        public ?float $salePrice,<br>        public int $categoryId,<br>        public ProductStatus $status,<br>        public ?array $metaData,<br>        public Carbon $createdAt,<br>        public Carbon $updatedAt,<br>        // Relationships<br>        public ?CategoryData $category = null,<br>        public ?array $media = null,<br>    ) {}<br>}</pre><h3>Dependency Injection &amp; Service Binding</h3><p><strong>Repository Service Provider</strong></p><pre>&lt;?php<br><br>namespace App\Providers;<br><br>use Illuminate\Support\ServiceProvider;<br>use App\Contracts\Repositories\ProductRepositoryInterface;<br>use App\Repositories\Eloquent\ProductRepository;<br><br>class RepositoryServiceProvider extends ServiceProvider<br>{<br>    public function register(): void<br>    {<br>        // Bind repositories as singletons for performance<br>        $this-&gt;app-&gt;singleton(<br>            ProductRepositoryInterface::class,<br>            ProductRepository::class<br>        );<br>    }<br>}</pre><p><strong>Service Service Provider</strong></p><pre>&lt;?php<br><br>namespace App\Providers;<br><br>use Illuminate\Support\ServiceProvider;<br>use App\Contracts\Services\ProductServiceInterface;<br>use App\Services\ProductService;<br><br>class ServicesServiceProvider extends ServiceProvider<br>{<br>    public function register(): void<br>    {<br>        // Bind services (not singletons - new instance per request)<br>        $this-&gt;app-&gt;bind(<br>            ProductServiceInterface::class,<br>            ProductService::class<br>        );<br>    }<br>}</pre><h3>Architecture Design Decisions &amp; Rationale</h3><p>Understanding the reasoning behind key architectural decisions is crucial for implementing this pattern effectively. Let me clarify two fundamental questions that often arise.</p><h4>Why Return DTOs Instead of Eloquent Models from Repositories?</h4><p>This is one of the most important design decisions in this Clean Service-Action architecture. Here’s why we return DTOs instead of Eloquent collections or models:</p><p><strong>1. Layer Separation &amp; Abstraction</strong></p><pre>// ❌ BAD: Repository returning Eloquent models<br>class ProductRepository implements ProductRepositoryInterface<br>{<br>    public function findByCategory(int $categoryId): Collection<br>    {<br>        return Product::where(&#39;category_id&#39;, $categoryId)-&gt;get(); // Exposes Eloquent<br>    }<br>}<br><br>// ✅ GOOD: Repository returning Collection of DTOs<br>class ProductRepository implements ProductRepositoryInterface<br>{<br>    public function findByCategory(int $categoryId): Collection<br>    {<br>        return Product::where(&#39;category_id&#39;, $categoryId)<br>            -&gt;get()<br>            -&gt;map(fn($product) =&gt; ProductData::from($product)); // Returns Collection of DTO instances<br>    }<br>}</pre><p><strong>Benefits:</strong></p><ul><li>Database Agnostic: Upper layers don’t know about Eloquent</li><li>Easy Testing: DTOs are simple data containers, easier to mock</li><li>Flexibility: Can switch from Eloquent to MongoDB, API calls, etc.</li></ul><p><strong>2. Prevents ORM Leakage</strong></p><p>First, let’s define the DTOs we’ll use in our examples:</p><pre>&lt;?php<br><br>// Supporting DTO classes for the examples<br>class ProductSummaryData extends Data<br>{<br>    public function __construct(<br>        public string $uuid,<br>        public string $name,<br>        public float $price<br>    ) {}<br>}<br><br>class ProductWithCategoryData extends Data<br>{<br>    public function __construct(<br>        public ProductData $product,<br>        public string $categoryName<br>    ) {}<br>}</pre><p>Now, here’s how proper layer separation prevents ORM leakage:</p><pre>// ❌ BAD: Service layer dealing with Eloquent relationships<br>class ProductService <br>{<br>    public function getProductsWithCategories(): Collection<br>    {<br>        $products = $this-&gt;repository-&gt;getAllProducts();<br>        <br>        // Service layer shouldn&#39;t know about Eloquent lazy loading<br>        $products-&gt;load(&#39;category&#39;); // This is ORM-specific knowledge!<br>        <br>        return $products;<br>    }<br>}<br><br>// ✅ GOOD: Service layer working with DTOs<br>class ProductService <br>{<br>    public function getProductsWithCategories(): array<br>    {<br>        $products = $this-&gt;repository-&gt;getAllProducts(); // Returns ProductData[]<br>        <br>        // Service works with clean DTOs, no ORM concerns<br>        return array_map(function(ProductData $product) {<br>            return new ProductWithCategoryData(<br>                product: $product,<br>                categoryName: $product-&gt;category?-&gt;name ?? &#39;Uncategorized&#39;<br>            );<br>        }, $products);<br>    }<br>}</pre><p><strong>3. Type Safety &amp; API Contracts</strong></p><pre>// ❌ BAD: Unclear return types<br>interface ProductRepositoryInterface<br>{<br>    public function findActive(): Collection; // What&#39;s in this collection?<br>}<br><br>// ✅ GOOD: Explicit type contracts with DTOs<br>interface ProductRepositoryInterface<br>{<br>    /**<br>     * Get all active products<br>     * @return Collection&lt;ProductData&gt;<br>     */<br>    public function findActive(): Collection; // Clear: Collection of ProductData instances<br>    <br>    /**<br>     * Find product by ID<br>     */<br>    public function findById(int $id): ?ProductData; // Clear: nullable ProductData DTO<br>}</pre><p><strong>4. Performance &amp; Memory Management</strong></p><pre>// ❌ BAD: Eloquent collections carry overhead<br>class ProductRepository<br>{<br>    public function getProductSummary(): Collection<br>    {<br>        return Product::with([&#39;category&#39;, &#39;media&#39;, &#39;reviews&#39;])<br>            -&gt;get(); // Heavy models with all relationships<br>    }<br>}<br><br>// ✅ GOOD: Lightweight DTOs with only needed data<br>class ProductRepository implements ProductRepositoryInterface<br>{<br>    /**<br>     * @return ProductSummaryData[]<br>     */<br>    public function getProductSummary(): array<br>    {<br>        return Product::select([&#39;id&#39;, &#39;uuid&#39;, &#39;name&#39;, &#39;price&#39;])<br>            -&gt;get()<br>            -&gt;map(fn($product) =&gt; new ProductSummaryData(<br>                uuid: $product-&gt;uuid,<br>                name: $product-&gt;name,<br>                price: $product-&gt;price<br>            ))<br>            -&gt;toArray(); // Returns array of ProductSummaryData DTOs<br>    }<br>    <br>    /**<br>     * @return Collection&lt;ProductData&gt;<br>     */<br>    public function findActive(): Collection<br>    {<br>        return Product::where(&#39;status&#39;, &#39;active&#39;)<br>            -&gt;get()<br>            -&gt;map(fn($product) =&gt; ProductData::from($product)); // Returns Collection of full ProductData DTOs<br>    }<br>}</pre><p><strong>5. Consistent Data Flow</strong></p><pre>// The entire flow uses DTOs for consistency:<br>// Request → FormRequest → DTO → Service → Action → Repository → DTO → Service → DTO → Controller → Resource<br><br>class ProductController<br>{<br>    public function store(CreateProductRequest $request)<br>    {<br>        // DTO in<br>        $productData = CreateProductData::from($request-&gt;validated());<br>        <br>        // DTO through the layers<br>        $product = $this-&gt;productService-&gt;createProduct($productData);<br>        <br>        // DTO out (via Resource)<br>        return new ProductResource($product); // ProductResource expects ProductData<br>    }<br>}</pre><h3><strong>Why Singletons for Repositories vs Regular Binding for Services?</strong></h3><p>This decision is based on the different lifecycle and state management needs of each layer.</p><h4>Repository Layer: Why Singletons</h4><pre>// Repositories are stateless data access objects<br>class ProductRepository implements ProductRepositoryInterface<br>{<br>    // No instance variables that change per request<br>    // No request-specific state<br>    // Pure data access methods<br>    <br>    public function findByUuid(string $uuid): ?ProductData<br>    {<br>        // This method doesn&#39;t depend on any instance state<br>        return Product::where(&#39;uuid&#39;, $uuid)<br>            -&gt;first()<br>            ?-&gt;pipe(fn($product) =&gt; ProductData::from($product));<br>    }<br>}<br><br>// Safe to share across requests<br>$this-&gt;app-&gt;singleton(ProductRepositoryInterface::class, ProductRepository::class);</pre><p><strong>Benefits of Repository Singletons:</strong></p><ul><li>Performance: One instance per application lifecycle</li><li>Memory Efficiency: Reduced object creation overhead</li><li>Stateless Nature: Repositories only contain query logic</li><li>Database Connection Reuse: Shared connection pooling</li></ul><h4>Service Layer: Why Regular Binding</h4><pre>// Services may hold request-specific state or context<br>class ProductService implements ProductServiceInterface<br>{<br>    private ?User $currentUser = null;<br>    private array $requestContext = [];<br>    <br>    public function setCurrentUser(User $user): void<br>    {<br>        $this-&gt;currentUser = $user; // Request-specific state!<br>    }<br>    <br>    public function createProduct(CreateProductData $data): ProductData<br>    {<br>        // Business logic may depend on current user context<br>        if ($this-&gt;currentUser?-&gt;cannot(&#39;create&#39;, Product::class)) {<br>            throw new UnauthorizedException();<br>        }<br>        <br>        // Process with user context...<br>    }<br>}<br><br>// Each request gets fresh instance<br>$this-&gt;app-&gt;bind(ProductServiceInterface::class, ProductService::class);</pre><p><strong>Why Services Need Fresh Instances:</strong></p><ul><li>Request Context: Services often hold user, tenant, or request-specific data</li><li>State Management: Business logic may accumulate state during request processing</li><li>Transaction Boundaries: Each request may have different transaction requirements</li><li>Memory Isolation: Prevents state leakage between requests</li></ul><h4>Practical Example: The Difference</h4><pre>// Repository: Stateless, safe to share<br>class UserRepository <br>{<br>    // This is safe as singleton - no state changes<br>    public function findById(int $id): ?UserData<br>    {<br>        return User::find($id)?-&gt;pipe(fn($u) =&gt; UserData::from($u));<br>    }<br>}<br><br>// Service: Stateful, needs fresh instances<br>class AuthService<br>{<br>    private ?User $authenticatedUser = null;<br>    private array $permissions = [];<br>    <br>    public function authenticate(string $token): User<br>    {<br>        // This changes the service&#39;s internal state<br>        $this-&gt;authenticatedUser = $this-&gt;validateToken($token);<br>        $this-&gt;permissions = $this-&gt;loadPermissions($this-&gt;authenticatedUser);<br>        <br>        return $this-&gt;authenticatedUser;<br>    }<br>    <br>    public function hasPermission(string $permission): bool<br>    {<br>        // Depends on the authenticated user from THIS request<br>        return in_array($permission, $this-&gt;permissions);<br>    }<br>}</pre><h4>Interface Binding Benefits</h4><pre>// Interface binding enables:<br><br>// 1. Easy Testing<br>class ProductServiceTest extends TestCase<br>{<br>    public function test_creates_product()<br>    {<br>        // Mock the interface, not the concrete class<br>        $mockRepo = Mockery::mock(ProductRepositoryInterface::class);<br>        $this-&gt;app-&gt;instance(ProductRepositoryInterface::class, $mockRepo);<br>        <br>        // Test proceeds with mocked dependencies<br>    }<br>}<br><br>// 2. Implementation Swapping<br>class AppServiceProvider extends ServiceProvider<br>{<br>    public function register()<br>    {<br>        if (config(&#39;app.use_api_repository&#39;)) {<br>            // Switch to API-based repository<br>            $this-&gt;app-&gt;singleton(<br>                ProductRepositoryInterface::class,<br>                ApiProductRepository::class<br>            );<br>        } else {<br>            // Use Eloquent repository<br>            $this-&gt;app-&gt;singleton(<br>                ProductRepositoryInterface::class,<br>                EloquentProductRepository::class<br>            );<br>        }<br>    }<br>}<br><br>// 3. Multiple Implementations<br>$this-&gt;app-&gt;when(ProductService::class)<br>    -&gt;needs(ProductRepositoryInterface::class)<br>    -&gt;give(EloquentProductRepository::class);<br><br>$this-&gt;app-&gt;when(ProductImportService::class)<br>    -&gt;needs(ProductRepositoryInterface::class)<br>    -&gt;give(CachedProductRepository::class);</pre><h4>Summary of Design Decisions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*N6ckuQSydqavz_OyQVw2Jg.png" /></figure><p>These decisions create a robust, testable, and maintainable architecture that scales well from small applications to enterprise systems.</p><h3>Testing Strategy</h3><p><strong>Unit Testing Actions</strong></p><pre>&lt;?php<br><br>namespace Tests\Unit\Actions\Product;<br><br>use Tests\TestCase;<br>use App\Actions\Product\CreateProduct;<br>use App\Contracts\Repositories\ProductRepositoryInterface;<br>use App\DTOs\Product\{CreateProductData, ProductData};<br>use App\Enum\ProductStatus;<br>use Carbon\Carbon;<br>use Mockery;<br><br>class CreateProductTest extends TestCase<br>{<br>    public function test_creates_product_successfully()<br>    {<br>        // Arrange<br>        $repository = Mockery::mock(ProductRepositoryInterface::class);<br>        $action = new CreateProduct($repository);<br>        <br>        $inputData = new CreateProductData(<br>            name: &#39;Test Product&#39;,<br>            sku: &#39;TEST001&#39;,<br>            description: &#39;Test Description&#39;,<br>            price: 99.99,<br>            salePrice: 79.99,<br>            categoryId: 1,<br>            status: ProductStatus::ACTIVE<br>        );<br>        <br>        $expectedProduct = new ProductData(<br>            id: 1,<br>            uuid: &#39;test-uuid-123&#39;,<br>            name: &#39;Test Product&#39;,<br>            sku: &#39;TEST001&#39;,<br>            description: &#39;Test Description&#39;,<br>            price: 99.99,<br>            salePrice: 79.99,<br>            categoryId: 1,<br>            status: ProductStatus::ACTIVE,<br>            metaData: null,<br>            createdAt: Carbon::now(),<br>            updatedAt: Carbon::now()<br>        );<br><br>        $repository-&gt;shouldReceive(&#39;create&#39;)<br>            -&gt;once()<br>            -&gt;with($inputData)<br>            -&gt;andReturn($expectedProduct);<br><br>        // Act<br>        $result = $action-&gt;execute($inputData);<br><br>        // Assert<br>        $this-&gt;assertEquals($expectedProduct, $result);<br>    }<br>}</pre><p><strong>Integration Testing Services</strong></p><pre>&lt;?php<br><br>&lt;?php<br><br>namespace Tests\Feature\Services;<br><br>use Tests\TestCase;<br>use App\Services\ProductService;<br>use App\DTOs\Product\CreateProductData;<br>use App\Models\{Product, Category};<br>use App\Enum\ProductStatus;<br>use Illuminate\Foundation\Testing\RefreshDatabase;<br><br>class ProductServiceTest extends TestCase<br>{<br>    use RefreshDatabase;<br><br>    public function test_creates_product_with_business_validation()<br>    {<br>        // Arrange<br>        $category = Category::factory()-&gt;create([&#39;status&#39; =&gt; &#39;active&#39;]);<br>        $service = app(ProductService::class);<br>        <br>        $productData = new CreateProductData(<br>            name: &#39;Test Product&#39;,<br>            sku: &#39;UNIQUE001&#39;,<br>            description: &#39;Test Description&#39;,<br>            price: 99.99,<br>            salePrice: null,<br>            categoryId: $category-&gt;id,<br>            status: ProductStatus::ACTIVE<br>        );<br><br>        // Act<br>        $result = $service-&gt;createProduct($productData);<br><br>        // Assert<br>        $this-&gt;assertDatabaseHas(&#39;products&#39;, [<br>            &#39;name&#39; =&gt; &#39;Test Product&#39;,<br>            &#39;sku&#39; =&gt; &#39;UNIQUE001&#39;<br>        ]);<br>        $this-&gt;assertEquals(&#39;Test Product&#39;, $result-&gt;name);<br>    }<br>}</pre><h4>Performance Considerations</h4><p><strong>Caching Strategies</strong></p><pre>// Service layer caching<br>public function getAllProducts(...$params): LengthAwarePaginator<br>{<br>    $cacheKey = &#39;products.&#39; . md5(serialize($params));<br>    <br>    return Cache::tags([&#39;products&#39;])-&gt;remember($cacheKey, 300, function () use ($params) {<br>        return $this-&gt;listProducts-&gt;execute(...$params);<br>    });<br>}<br><br>// Repository query optimization<br>public function getPaginated(...$params): LengthAwarePaginator<br>{<br>    return Product::query()<br>        -&gt;select([&#39;id&#39;, &#39;uuid&#39;, &#39;name&#39;, &#39;price&#39;]) // Only needed columns<br>        -&gt;with([&#39;category:id,name&#39;]) // Eager load relationships<br>        -&gt;when($search, fn($q) =&gt; $q-&gt;where(&#39;name&#39;, &#39;LIKE&#39;, &quot;%{$search}%&quot;))<br>        -&gt;paginate($perPage);<br>}</pre><p><strong>Database Optimization</strong></p><pre>// Repository with optimized queries<br>class ProductRepository implements ProductRepositoryInterface<br>{<br>    public function getPopularProducts(int $limit = 10): Collection<br>    {<br>        return Product::query()<br>            -&gt;select([&#39;id&#39;, &#39;uuid&#39;, &#39;name&#39;, &#39;price&#39;])<br>            -&gt;withCount(&#39;orders&#39;)<br>            -&gt;orderBy(&#39;orders_count&#39;, &#39;desc&#39;)<br>            -&gt;limit($limit)<br>            -&gt;get()<br>            -&gt;map(fn($product) =&gt; ProductData::from($product));<br>    }<br>}</pre><h3>Advanced Patterns &amp; Best Practices</h3><p><strong>Event-Driven Actions</strong></p><pre>&lt;?php<br><br>namespace App\Actions\Product;<br><br>use App\Events\ProductCreated;<br>use App\Contracts\Repositories\ProductRepositoryInterface;<br>use App\DTOs\Product\{CreateProductData, ProductData};<br><br>readonly class CreateProduct<br>{<br>    public function __construct(<br>        private ProductRepositoryInterface $productRepository<br>    ) {}<br><br>    public function execute(CreateProductData $data): ProductData<br>    {<br>        $product = $this-&gt;productRepository-&gt;create($data);<br>        <br>        // Dispatch event for side effects<br>        event(new ProductCreated($product));<br>        <br>        return $product;<br>    }<br>}</pre><p><strong>Policy-Based Actions</strong></p><pre>&lt;?php<br><br>namespace App\Actions\Product;<br><br>use App\Contracts\Repositories\ProductRepositoryInterface;<br>use App\DTOs\Product\UpdateProductData;<br>use Illuminate\Support\Facades\Gate;<br><br>readonly class UpdateProduct<br>{<br>    public function __construct(<br>        private ProductRepositoryInterface $productRepository<br>    ) {}<br><br>    public function execute(string $uuid, UpdateProductData $data, User $user): ProductData<br>    {<br>        $product = $this-&gt;productRepository-&gt;findByUuid($uuid);<br>        <br>        Gate::authorize(&#39;update&#39;, $product);<br>        <br>        return $this-&gt;productRepository-&gt;updateByUuid($uuid, $data);<br>    }<br>}</pre><h3>Exception Handling Strategy</h3><p>A robust exception handling strategy is crucial for maintaining application reliability and providing meaningful error responses. This Clean Service-Action architecture implements a multi-layered exception handling approach that ensures consistent error management across all layers.</p><h4>Custom Exception Hierarchy</h4><p>The foundation of our exception handling is a custom exception base class that provides structured error codes and messages:</p><pre>&lt;?php<br><br>namespace App\Exceptions;<br><br>use App\Enum\{ErrorCode, ErrorMessage};<br>use Exception;<br>use Illuminate\Support\Facades\Log;<br><br>class CustomExceptionBase extends Exception<br>{<br>    protected array $context = [];<br>    protected ?string $userMessage = null;<br><br>    public function __construct(<br>        protected ?ErrorCode $customCode = null,<br>        protected ?ErrorMessage $customMessage = null,<br>        $errors = null,<br>        ?string $userMessage = null,<br>        array $context = []<br>    ) {<br>        $message = $errors ?: $customMessage?-&gt;value ?? ErrorMessage::InternalServerError-&gt;value;<br>        $this-&gt;userMessage = $userMessage;<br>        $this-&gt;context = $context;<br>        <br>        parent::__construct($message);<br>    }<br><br>    /**<br>     * Get the custom error code<br>     */<br>    public function getErrorCode(): ErrorCode<br>    {<br>        return $this-&gt;customCode ?? ErrorCode::UnknownError;<br>    }<br><br>    /**<br>     * Get the custom error message enum<br>     */<br>    public function getErrorMessage(): ErrorMessage<br>    {<br>        return $this-&gt;customMessage ?? ErrorMessage::InternalServerError;<br>    }<br><br>    /**<br>     * Get the error code as string<br>     */<br>    public function getErrorCodeStr(): string<br>    {<br>        return $this-&gt;customCode?-&gt;value ?? ErrorCode::UnknownError-&gt;value;<br>    }<br><br>    /**<br>     * Get user-friendly message (for API responses)<br>     */<br>    public function getUserMessage(): string<br>    {<br>        return $this-&gt;userMessage ?? $this-&gt;getErrorMessage()-&gt;value;<br>    }<br><br>    /**<br>     * Get additional context information<br>     */<br>    public function getContext(): array<br>    {<br>        return $this-&gt;context;<br>    }<br><br>    /**<br>     * Set additional context<br>     */<br>    public function setContext(array $context): static<br>    {<br>        $this-&gt;context = array_merge($this-&gt;context, $context);<br>        return $this;<br>    }<br><br>    /**<br>     * Report this exception to logs<br>     */<br>    public function report(): void<br>    {<br>        Log::error(&#39;Custom exception occurred&#39;, [<br>            &#39;exception_class&#39; =&gt; static::class,<br>            &#39;error_code&#39; =&gt; $this-&gt;getErrorCodeStr(),<br>            &#39;error_message&#39; =&gt; $this-&gt;getErrorMessage()-&gt;value,<br>            &#39;user_message&#39; =&gt; $this-&gt;getUserMessage(),<br>            &#39;context&#39; =&gt; $this-&gt;getContext(),<br>            &#39;file&#39; =&gt; $this-&gt;getFile(),<br>            &#39;line&#39; =&gt; $this-&gt;getLine(),<br>            &#39;trace&#39; =&gt; $this-&gt;getTraceAsString()<br>        ]);<br>    }<br><br>    /**<br>     * Convert to array for JSON responses<br>     */<br>    public function toArray(): array<br>    {<br>        return [<br>            &#39;code&#39; =&gt; $this-&gt;getErrorCodeStr(),<br>            &#39;message&#39; =&gt; $this-&gt;getUserMessage(),<br>            &#39;context&#39; =&gt; $this-&gt;getContext(),<br>        ];<br>    }<br>}</pre><p><strong>Usage Examples of CustomExceptionBase</strong></p><p>Here are practical examples of how to use the `CustomExceptionBase` in different scenarios:</p><pre>&lt;?php<br><br>namespace App\Actions\Product;<br><br>use App\Exceptions\CustomExceptionBase;<br>use App\Enum\{ErrorCode, ErrorMessage};<br><br>class ValidateStockQuantity<br>{<br>    public function execute(int $productId, int $requestedQuantity): void<br>    {<br>        $availableStock = $this-&gt;getAvailableStock($productId);<br>        <br>        if ($requestedQuantity &gt; $availableStock) {<br>            throw new CustomExceptionBase(<br>                customCode: ErrorCode::InsufficientStock,<br>                customMessage: ErrorMessage::InsufficientStock,<br>                userMessage: &quot;Only {$availableStock} items available in stock&quot;,<br>                context: [<br>                    &#39;product_id&#39; =&gt; $productId,<br>                    &#39;requested_quantity&#39; =&gt; $requestedQuantity,<br>                    &#39;available_stock&#39; =&gt; $availableStock,<br>                    &#39;shortfall&#39; =&gt; $requestedQuantity - $availableStock<br>                ]<br>            );<br>        }<br>    }<br>}</pre><pre>&lt;?php<br><br>namespace App\Services\External;<br><br>use App\Exceptions\CustomExceptionBase;<br>use App\Enum\{ErrorCode, ErrorMessage};<br>use Illuminate\Support\Facades\Http;<br><br>class PaymentGatewayService<br>{<br>    public function processPayment(array $paymentData): array<br>    {<br>        try {<br>            $response = Http::timeout(30)-&gt;post($this-&gt;gatewayUrl, $paymentData);<br>            <br>            if (!$response-&gt;successful()) {<br>                throw new CustomExceptionBase(<br>                    customCode: ErrorCode::ExternalServiceError,<br>                    customMessage: ErrorMessage::ExternalServiceError,<br>                    userMessage: &#39;Payment processing is temporarily unavailable&#39;,<br>                    context: [<br>                        &#39;gateway_response_code&#39; =&gt; $response-&gt;status(),<br>                        &#39;gateway_response_body&#39; =&gt; $response-&gt;body(),<br>                        &#39;payment_amount&#39; =&gt; $paymentData[&#39;amount&#39;] ?? &#39;unknown&#39;,<br>                        &#39;transaction_id&#39; =&gt; $paymentData[&#39;transaction_id&#39;] ?? null<br>                    ]<br>                );<br>            }<br>            <br>            return $response-&gt;json();<br>        } catch (Exception $e) {<br>            if ($e instanceof CustomExceptionBase) {<br>                throw $e; // Re-throw custom exceptions<br>            }<br>            <br>            // Wrap unexpected exceptions<br>            throw new CustomExceptionBase(<br>                customCode: ErrorCode::ExternalServiceError,<br>                customMessage: ErrorMessage::ExternalServiceError,<br>                userMessage: &#39;Payment service is currently unavailable&#39;,<br>                context: [<br>                    &#39;original_exception&#39; =&gt; get_class($e),<br>                    &#39;original_message&#39; =&gt; $e-&gt;getMessage(),<br>                    &#39;payment_data&#39; =&gt; $paymentData<br>                ]<br>            );<br>        }<br>    }<br>}</pre><p><strong>Domain-Specific Exceptions</strong></p><p>Each domain has its own exception classes for better error categorization:</p><pre>&lt;?php<br><br>namespace App\Exceptions;<br><br>// Product-specific exceptions<br>class ProductException extends CustomExceptionBase<br>{<br>    // Inherit all base functionality<br>}<br><br>// Order processing exceptions<br>class OrderException extends CustomExceptionBase<br>{<br>    // Inherit all base functionality<br>}<br><br>// Business rule violations<br>class BusinessRuleException extends CustomExceptionBase<br>{<br>    // Inherit all base functionality<br>}<br><br>// External API integration exceptions<br>class ExternalServiceException extends CustomExceptionBase<br>{<br>    // Inherit all base functionality<br>}</pre><h4><strong>HTTP Exception Handler</strong></h4><p>For API responses, we use a specialized HTTP exception that provides consistent error formatting:</p><pre>&lt;?php<br><br>namespace App\Exceptions;<br><br>use App\Enum\{ErrorCode, ErrorMessage};<br>use Exception;<br>use Illuminate\Http\{Request, Response};<br>use Illuminate\Support\Str;<br>use Symfony\Component\HttpFoundation\Response as ResponseAlias;<br><br>class ResponseHttpException extends Exception<br>{<br>    public function __construct(<br>        protected ErrorCode|null $customCode = null,<br>        protected null|string|ErrorMessage $customMessage = null,<br>        protected ?int $httpCode = ResponseAlias::HTTP_INTERNAL_SERVER_ERROR,<br>        $errors = null,<br>        $code = 0,<br>        Exception $previous = null<br>    ) {<br>        parent::__construct($errors, $code, $previous);<br>    }<br><br>    public function render(Request $request): Response<br>    {<br>        $code = $this-&gt;customCode?-&gt;value ?? ErrorCode::InternalServerError-&gt;value;<br>        <br>        $response = [<br>            &#39;code&#39; =&gt; $code,<br>            &#39;title&#39; =&gt; Str::snakeToTitle($code) . &quot;!&quot;,<br>            &#39;message&#39; =&gt; $this-&gt;customMessage instanceof \UnitEnum <br>                ? $this-&gt;customMessage-&gt;value <br>                : (is_string($this-&gt;customMessage) <br>                    ? $this-&gt;customMessage <br>                    : ErrorMessage::InternalServerError-&gt;value),<br>        ];<br><br>        if (config(&#39;app.debug&#39;)) {<br>            $response[&#39;errors&#39;] = $this-&gt;getMessage();<br>            $response[&#39;trace&#39;] = $this-&gt;getTraceAsString();<br>        }<br><br>        return response()-&gt;json($response, $this-&gt;httpCode);<br>    }<br>}</pre><h4>Exception Handling in Each Layer</h4><p><strong>Controller Level Exception Handling</strong></p><p>Controllers catch exceptions and convert them to appropriate HTTP responses:</p><pre>public function store(CreateProductRequest $request)<br>{<br>    try {<br>        $productData = CreateProductData::from($request-&gt;validated());<br>        $product = $this-&gt;productService-&gt;createProduct($productData);<br>        <br>        return (new ProductResource($product))<br>            -&gt;response()<br>            -&gt;setStatusCode(Response::HTTP_CREATED);<br>    } catch (BusinessRuleException $e) {<br>        throw new ResponseHttpException(<br>            ErrorCode::BusinessRuleViolation,<br>            $e-&gt;getMessage(),<br>            Response::HTTP_UNPROCESSABLE_ENTITY<br>        );<br>    } catch (OrderException $e) {<br>        throw new ResponseHttpException(<br>            $e-&gt;getErrorCode(),<br>            $e-&gt;getErrorMessage(),<br>            Response::HTTP_BAD_REQUEST<br>        );<br>    } catch (Exception $e) {<br>        Log::error(&#39;Unexpected error in product creation&#39;, [<br>            &#39;error&#39; =&gt; $e-&gt;getMessage(),<br>            &#39;trace&#39; =&gt; $e-&gt;getTraceAsString()<br>        ]);<br>        <br>        throw new ResponseHttpException(<br>            ErrorCode::CreationFailed,<br>            ErrorMessage::CreationFailed,<br>            Response::HTTP_INTERNAL_SERVER_ERROR<br>        );<br>    }<br>}</pre><p><strong>Service Level Exception Handling</strong></p><p>Services handle business logic exceptions and provide transaction rollback:</p><pre>public function createProduct(CreateProductData $data): ProductData<br>{<br>    return DB::transaction(function () use ($data) {<br>        try {<br>            // Validate business rules<br>            $this-&gt;validateProductData-&gt;execute($data);<br>            <br>            // Create the product<br>            $product = $this-&gt;createProduct-&gt;execute($data);<br>            <br>            // Clear related caches<br>            Cache::tags([&#39;products&#39;, &#39;categories&#39;])-&gt;flush();<br>            <br>            return $product;<br>        } catch (BusinessRuleException $e) {<br>            // Business rule violations - let them bubble up<br>            throw $e;<br>        } catch (QueryException $e) {<br>            Log::error(&#39;Database error during product creation&#39;, [<br>                &#39;error&#39; =&gt; $e-&gt;getMessage(),<br>                &#39;data&#39; =&gt; $data-&gt;toArray()<br>            ]);<br>            <br>            throw new BusinessRuleException(<br>                ErrorCode::DatabaseError,<br>                ErrorMessage::DatabaseError<br>            );<br>        } catch (Exception $e) {<br>            Log::error(&#39;Unexpected error in service layer&#39;, [<br>                &#39;error&#39; =&gt; $e-&gt;getMessage(),<br>                &#39;service&#39; =&gt; static::class,<br>                &#39;method&#39; =&gt; &#39;createProduct&#39;<br>            ]);<br>            <br>            throw new BusinessRuleException(<br>                ErrorCode::InternalServerError,<br>                ErrorMessage::InternalServerError<br>            );<br>        }<br>    });<br>}</pre><p><strong>Action Level Exception Handling</strong></p><p>Actions handle specific business logic errors:</p><pre>readonly class ValidateProductData<br>{<br>    public function execute(CreateProductData $data, ?ProductData $existingProduct = null): void<br>    {<br>        try {<br>            // Check for duplicate SKU<br>            if ($this-&gt;productRepository-&gt;existsBySku($data-&gt;sku, $existingProduct?-&gt;id)) {<br>                throw new BusinessRuleException(<br>                    ErrorCode::DuplicateEntry,<br>                    ErrorMessage::DuplicateEntry<br>                );<br>            }<br><br>            // Validate category exists and is active<br>            $category = $this-&gt;categoryRepository-&gt;findById($data-&gt;categoryId);<br>            if (!$category) {<br>                throw new BusinessRuleException(<br>                    ErrorCode::NotFound,<br>                    ErrorMessage::CategoryNotFound<br>                );<br>            }<br><br>            if (!$category-&gt;isActive) {<br>                throw new BusinessRuleException(<br>                    ErrorCode::ValidationFailed,<br>                    ErrorMessage::InactiveCategory<br>                );<br>            }<br><br>            // Business rule validations<br>            if ($data-&gt;price &lt;= 0) {<br>                throw new BusinessRuleException(<br>                    ErrorCode::ValidationFailed,<br>                    ErrorMessage::InvalidPrice<br>                );<br>            }<br><br>            if ($data-&gt;salePrice &amp;&amp; $data-&gt;salePrice &gt;= $data-&gt;price) {<br>                throw new BusinessRuleException(<br>                    ErrorCode::ValidationFailed,<br>                    ErrorMessage::InvalidSalePrice<br>                );<br>            }<br>        } catch (Exception $e) {<br>            Log::warning(&#39;Product validation failed&#39;, [<br>                &#39;data&#39; =&gt; $data-&gt;toArray(),<br>                &#39;error&#39; =&gt; $e-&gt;getMessage()<br>            ]);<br>            throw $e;<br>        }<br>    }<br>}</pre><p><strong>Repository Level Exception Handling</strong></p><p>Repositories handle data access exceptions and provide meaningful error context:</p><pre>public function create(CreateProductData $data): ProductData<br>{<br>    try {<br>        $product = Product::create([<br>            &#39;name&#39; =&gt; $data-&gt;name,<br>            &#39;sku&#39; =&gt; $data-&gt;sku,<br>            &#39;description&#39; =&gt; $data-&gt;description,<br>            &#39;price&#39; =&gt; $data-&gt;price,<br>            &#39;sale_price&#39; =&gt; $data-&gt;salePrice,<br>            &#39;category_id&#39; =&gt; $data-&gt;categoryId,<br>            &#39;status&#39; =&gt; $data-&gt;status,<br>            &#39;meta_data&#39; =&gt; $data-&gt;metaData,<br>        ]);<br><br>        return ProductData::from($product-&gt;load(&#39;category&#39;));<br>    } catch (QueryException $e) {<br>        // Handle specific database errors<br>        if ($e-&gt;getCode() === &#39;23000&#39;) { // Duplicate entry<br>            throw new BusinessRuleException(<br>                ErrorCode::DuplicateEntry,<br>                &#39;Product with this SKU already exists&#39;<br>            );<br>        }<br><br>        // Log database errors for debugging<br>        Log::error(&#39;Database query failed in ProductRepository&#39;, [<br>            &#39;method&#39; =&gt; &#39;create&#39;,<br>            &#39;error&#39; =&gt; $e-&gt;getMessage(),<br>            &#39;sql&#39; =&gt; $e-&gt;getSql(),<br>            &#39;bindings&#39; =&gt; $e-&gt;getBindings()<br>        ]);<br><br>        // Re-throw for service layer handling<br>        throw $e;<br>    } catch (Exception $e) {<br>        Log::error(&#39;Unexpected error in ProductRepository&#39;, [<br>            &#39;method&#39; =&gt; &#39;create&#39;,<br>            &#39;error&#39; =&gt; $e-&gt;getMessage(),<br>            &#39;data&#39; =&gt; $data-&gt;toArray()<br>        ]);<br>        throw $e;<br>    }<br>}</pre><h4>Error Code and Message Enums</h4><p>Using enums for consistent error codes and messages:</p><pre>&lt;?php<br><br>namespace App\Enum;<br><br>enum ErrorCode: string<br>{<br>    case ValidationFailed = &#39;validation_failed&#39;;<br>    case NotFound = &#39;not_found&#39;;<br>    case DuplicateEntry = &#39;duplicate_entry&#39;;<br>    case BusinessRuleViolation = &#39;business_rule_violation&#39;;<br>    case InsufficientStock = &#39;insufficient_stock&#39;;<br>    case DatabaseError = &#39;database_error&#39;;<br>    case ExternalServiceError = &#39;external_service_error&#39;;<br>    case InternalServerError = &#39;internal_server_error&#39;;<br>    case UnknownError = &#39;unknown_error&#39;;<br>    case CreationFailed = &#39;creation_failed&#39;;<br>}<br><br>enum ErrorMessage: string<br>{<br>    case ValidationFailed = &#39;The provided data is invalid&#39;;<br>    case NotFound = &#39;The requested resource was not found&#39;;<br>    case DuplicateEntry = &#39;A record with this information already exists&#39;;<br>    case BusinessRuleViolation = &#39;This operation violates business rules&#39;;<br>    case InsufficientStock = &#39;Insufficient stock to complete the operation&#39;;<br>    case DatabaseError = &#39;A database error occurred&#39;;<br>    case ExternalServiceError = &#39;External service is unavailable&#39;;<br>    case InternalServerError = &#39;An internal server error occurred&#39;;<br>    case CreationFailed = &#39;Failed to create the resource&#39;;<br>    case CategoryNotFound = &#39;The specified category was not found&#39;;<br>    case InactiveCategory = &#39;The category is not active&#39;;<br>    case InvalidPrice = &#39;The price must be greater than zero&#39;;<br>    case InvalidSalePrice = &#39;Sale price must be lower than regular price&#39;;<br>}</pre><h4>Exception Handling Benefits</h4><ul><li>Consistent Error Responses — Standardized error format across all APIs</li><li>Type-Safe Error Codes — Enum-based error classification prevents typos</li><li>Contextual Information — Domain-specific exception details</li><li>Proper HTTP Status Codes — REST-compliant error responses</li><li>Comprehensive Logging — Detailed error tracking for debugging</li><li>Debug Support — Enhanced error details in development mode</li><li>Transaction Safety — Automatic rollback on exceptions</li><li>Error Propagation — Controlled error bubbling between layers</li></ul><p><strong>Global Exception Handler</strong></p><p>Register custom exceptions in `app/Exceptions/Handler.php`:</p><pre>public function register(): void<br>{<br>    $this-&gt;reportable(function (CustomExceptionBase $e) {<br>        Log::error(&#39;Custom exception occurred&#39;, [<br>            &#39;exception&#39; =&gt; get_class($e),<br>            &#39;code&#39; =&gt; $e-&gt;getErrorCodeStr(),<br>            &#39;message&#39; =&gt; $e-&gt;getMessage(),<br>            &#39;trace&#39; =&gt; $e-&gt;getTraceAsString()<br>        ]);<br>    });<br>}</pre><p>This exception handling strategy ensures that errors are properly caught, logged, and converted to meaningful responses while maintaining the integrity of the application’s business logic and data consistency.</p><h3>Common Pitfalls and How to Avoid Them</h3><h4><strong>1. Over-Engineering Small Features</strong></h4><pre>// ❌ AVOID: Creating full architecture for simple CRUD<br>class GetUserNameAction<br>{<br>    public function execute(int $userId): string<br>    {<br>        return User::find($userId)?-&gt;name ?? &#39;Unknown&#39;;<br>    }<br>}<br><br>// ✅ BETTER: Use simple eloquent for basic operations<br>class UserController<br>{<br>    public function getName(int $userId): JsonResponse<br>    {<br>        $name = User::find($userId)?-&gt;name ?? &#39;Unknown&#39;;<br>        return response()-&gt;json([&#39;name&#39; =&gt; $name]);<br>    }<br>}</pre><p><strong>Rule of Thumb:</strong> Use this Clean Service-Action architecture for complex business logic, not simple CRUD operations.</p><h4>2. Creating Anemic Actions</h4><pre>// ❌ AVOID: Actions that just call repository methods<br>class GetProduct<br>{<br>    public function execute(string $uuid): ?ProductData<br>    {<br>        return $this-&gt;repository-&gt;findByUuid($uuid);<br>    }<br>}<br><br>// ✅ BETTER: Actions with actual business logic<br>class GetProductWithRecommendations<br>{<br>    public function execute(string $uuid, ?User $user = null): ProductWithRecommendationsData<br>    {<br>        $product = $this-&gt;repository-&gt;findByUuid($uuid);<br>        $recommendations = $this-&gt;recommendationService-&gt;getForProduct($product, $user);<br>        <br>        return new ProductWithRecommendationsData(<br>            product: $product,<br>            recommendations: $recommendations<br>        );<br>    }<br>}</pre><h4>3. Repository Query Leakage</h4><pre>// ❌ AVOID: Exposing query builders<br>interface ProductRepositoryInterface<br>{<br>    public function query(): Builder; // Exposes Eloquent<br>}<br><br>// ✅ BETTER: Specific, purposeful methods<br>interface ProductRepositoryInterface<br>{<br>    public function findActiveByCategory(int $categoryId, int $limit = 10): array;<br>    public function findExpiringSoon(int $days = 7): array;<br>}</pre><h3>Conclusion and Next Steps</h3><p>This Clean Service-Action architecture pattern represents a mature approach to Laravel application development, balancing simplicity with scalability. Here’s how to get started:</p><h4>Immediate Actions</h4><ol><li><strong>Choose a single feature</strong> to implement with this pattern</li><li><strong>Set up the recommended packages</strong> (spatie/laravel-data, spatie/laravel-queueable-action)</li><li><strong>Create your first DTO</strong> and Service interface</li><li><strong>Write tests</strong> as you implement each layer</li></ol><h4>Long-term Benefits</h4><ul><li><strong>Reduced debugging time —</strong> Clear error boundaries</li><li><strong>Faster feature development —</strong> Reusable components</li><li><strong>Easier team onboarding </strong>— Consistent patterns</li><li><strong>Improved code quality </strong>— Enforced separation of concerns</li></ul><h4>When NOT to Use This Pattern</h4><ul><li>Simple CRUD applications with minimal business logic</li><li>Prototypes or proof-of-concept projects</li><li>Applications with very tight deadlines and simple requirements</li></ul><h4>Further Reading and Resources</h4><ul><li><a href="https://laravel.com/docs/12.x/container">Service Container — Laravel 12.x</a></li><li><a href="https://leanpub.com/ddd-in-php">https://leanpub.com/ddd-in-php</a></li><li><a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html</a></li><li><a href="https://spatie.be/docs/laravel-data">https://spatie.be/docs/laravel-data</a></li></ul><p><strong>This Clean Service-Action architecture pattern has been battle-tested across multiple production Laravel applications, serving millions of requests while maintaining code quality and developer productivity. The investment in proper structure pays dividends as your application grows and evolves.</strong></p><p><strong>Have questions about implementing this pattern? Feel free to reach out in the comments below or connect with me on </strong><a href="https://www.linkedin.com/in/ratheeps/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc311ecc5c29" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>