Search code examples
phplaravellaravel-11

Laravel 11 - Builder classes, their location and design


Say in Laravel 11, I need few classes that will only serve as doing something with some parameters and returning them in a joined string. How would you approach this, what would be the design and under what namespaces would you store them?

<?php

namespace App\Where?;

readonly class SomethingBuilder
{
    public function __construct(
        private string $value
    ) {}

    public function __invoke(): string
    {
        // Do something with the string
    }
}

Solution

  • Although there is no universal correct way to execute this, But in my opinion, if you need a few classes that are responsible for processing parameters and returning a joined string (or similar tasks), this typically falls under the domain of service classes or utility classes. The design depends on how you intend to use these classes, but here is a general approach:

    1. Designing the Class

    Given that the class will "do something" with parameters and return a joined string, you can approach this as a value object or a builder pattern. Your SomethingBuilder class can be designed as follows:

    <?php
    
    namespace App\Services\Builders;
    
    readonly class SomethingBuilder
    {
        public function __construct(
            private string $value
        ) {}
    
        public function __invoke(): string
        {
            // Process the string and return the result
            return $this->processValue();
        }
    
        private function processValue(): string
        {
            // Perform some operations on $this->value
            // For example, concatenate or transform the string
            return "Processed: " . $this->value;
        }
    }
    

    2. Where to Place the Class

    The placement of the class depends on its role in your application:

    Services or Utility Classes: If the class is doing something that can be categorized as a service (e.g., building or processing strings), you should place it under the App\Services or App\Support namespace.

    App\Services\Builders: If you want to treat it as a part of a service layer, particularly if you foresee multiple related classes handling similar tasks. App\Support\Builders: If you think of this class as more of a general utility, not directly tied to the service layer.