> For the complete documentation index, see [llms.txt](https://al-mamun.gitbook.io/al-mamun/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://al-mamun.gitbook.io/al-mamun/design-patterns/builder-and-strategy-pattern.md).

# Builder & Strategy Pattern

## Builder & Strategy Pattern in Laravel Reporting System

Modern reporting systems often become complex very quickly—multiple filters, dynamic data sources, export formats, and business rules. If not designed properly, the code turns into a mess of `if-else` conditions and tightly coupled logic.

Two design patterns that can significantly improve your Laravel reporting architecture are:

* **Builder Pattern** → for constructing complex reports step-by-step
* **Strategy Pattern** → for handling interchangeable business logic (filters, formats, calculations)

Let’s break them down with real Laravel use cases.

***

## 1. Builder Pattern in Laravel Reporting

### 🧠 Problem

In reporting systems, you often need to dynamically build queries like:

* Filter by date range
* Filter by user / branch / status
* Add joins conditionally
* Apply sorting, grouping

If you handle everything inside one method, it becomes unmaintainable.

***

### ✅ Solution: Builder Pattern

The Builder Pattern helps you **construct complex queries step-by-step**, keeping your code modular and readable.

***

### 🏗 Example: Report Builder Class

```php
class SalesReportBuilder
{
    protected $query;

    public function __construct()
    {
        $this->query = DB::table('orders');
    }

    public function filterByDate($from, $to)
    {
        $this->query->whereBetween('created_at', [$from, $to]);
        return $this;
    }

    public function filterByStatus($status)
    {
        $this->query->where('status', $status);
        return $this;
    }

    public function filterByUser($userId)
    {
        $this->query->where('user_id', $userId);
        return $this;
    }

    public function withTotalAmount()
    {
        $this->query->selectRaw('SUM(amount) as total');
        return $this;
    }

    public function get()
    {
        return $this->query->get();
    }
}
```

***

### 🚀 Usage

```
$report = (new SalesReportBuilder())
    ->filterByDate($from, $to)
    ->filterByStatus('completed')
    ->withTotalAmount()
    ->get();
```

***

### 💡 Benefits

* Clean and readable
* Reusable query parts
* Easy to extend (add new filters without breaking code)
* Avoids massive controller logic

***

## 2. Strategy Pattern in Laravel Reporting

### 🧠 Problem

Reports often vary in behavior:

* Different calculation logic (commission, profit, tax)
* Different export formats (PDF, Excel, CSV)
* Different grouping logic

Using `if-else` everywhere makes code fragile.

***

### ✅ Solution: Strategy Pattern

The Strategy Pattern allows you to **swap algorithms dynamically**.

***

### 🧩 Example: Report Calculation Strategy

#### Step 1: Create Interface

```
interface ReportStrategy
{
    public function process($data);
}
```

***

#### Step 2: Create Concrete Strategies

**Profit Report**

```
class ProfitStrategy implements ReportStrategy
{
    public function process($data)
    {
        return $data->sum('amount') - $data->sum('cost');
    }
}
```

**Commission Report**

```
class CommissionStrategy implements ReportStrategy
{
    public function process($data)
    {
        return $data->sum('commission');
    }
}
```

***

#### Step 3: Context Class

```
class ReportService
{
    protected $strategy;

    public function __construct(ReportStrategy $strategy)
    {
        $this->strategy = $strategy;
    }

    public function generate($data)
    {
        return $this->strategy->process($data);
    }
}
```

***

### 🚀 Usage

```
$data = DB::table('orders')->get();

// dynamically choose strategy
$strategy = new ProfitStrategy();

$service = new ReportService($strategy);

$result = $service->generate($data);
```

***

### 💡 Benefits

* Removes complex conditional logic
* Easy to add new report types
* Follows Open/Closed Principle (no modification needed, just extend)

***

## 3. Combining Builder + Strategy (Best Practice)

In real Laravel systems, you should combine both patterns:

#### 🔥 Flow

1. **Builder → prepares data (query)**
2. **Strategy → processes data (business logic)**

***

### 🧱 Combined Example

```
$builder = (new SalesReportBuilder())
    ->filterByDate($from, $to)
    ->filterByStatus('completed');

$data = $builder->get();

// dynamic strategy selection
$strategy = match($type) {
    'profit' => new ProfitStrategy(),
    'commission' => new CommissionStrategy(),
};

$result = (new ReportService($strategy))->generate($data);
```

***

## 4. Real-Life Use Cases in Laravel Projects

You can apply this in:

#### 📊 ERP / Garments System

* Production reports
* Line efficiency reports
* Cost analysis

#### 🛒 E-commerce

* Sales reports
* Customer insights
* Revenue analytics

***

## 5. Pro Tips (From Production Experience)

* Use **DTOs or Collections** instead of raw arrays
* Cache heavy reports (`Redis`)
* Use **chunking / cursor** for large data
* Separate:
  * Query (Builder)
  * Logic (Strategy)
  * Output (Transformer / Export)

***

## ✅ Conclusion

Using Builder and Strategy patterns in Laravel reporting systems helps you:

* Keep code clean and scalable
* Reduce duplication
* Handle complex business logic elegantly
* Easily extend features without breaking existing code
