Ionut Paduraru
Ionut Paduraru

Reputation: 37

Laravel design patterns

I have a little hard time with all of those design patterns and things that could help me write maintainable code, clean and reusable.What are the most used design patterns in your Apps? A list or something with them will be nice, there are a lot of design patterns and I dont really know with what should I start.

Upvotes: 0

Views: 4556

Answers (2)

Md. Saifur Rahman
Md. Saifur Rahman

Reputation: 404

Builder Design Pattern in laravel

PricingBuilder.php

<?php

namespace App\Builders;

class PricingBuilder
{
    private $orderPrice;
    private $discount;
    private $taxPercent;
    private $shippingFee;

    public function setOrderPrice($orderPrice): PricingBuilder
    {
        $this->orderPrice = $orderPrice;
        return $this;
    }

    public function setDiscount($discount): PricingBuilder
    {
        $this->discount = $discount;
        return $this;
    }

    public function setTaxPercent($taxPercent): PricingBuilder
    {
        $this->taxPercent = $taxPercent;
        return $this;
    }

    public function setShippingFee($shippingFee): PricingBuilder
    {
        $this->shippingFee = $shippingFee;
        return $this;
    }

    function calculateTotalPrice()
    {
        return $this->orderPrice - $this->discount + ($this->orderPrice*($this->taxPercent/100)) + $this->shippingFee;
    }
}

BuilderController.php

<?php
namespace App\Http\Controllers\DesignPattern\Builder;

use App\Traits\ApiResponser;
use Illuminate\Http\Request;
use App\Builders\PricingBuilder;
use App\Http\Controllers\Controller;

class BuilderController extends Controller
{
    use ApiResponser;
    public function pricingTest(Request $request, PricingBuilder $pricingBuilder)
    {
        $data = $pricingBuilder
                ->setOrderPrice(500)
                ->setDiscount(15)
                ->setTaxPercent(5)
                ->setShippingFee(80)
                ->calculateTotalPrice();

        return $this->set_response($data, 200,'success', ['Price calculation building!']);
    }
}

Strategy Design Pattern in larave

StrategyController.php
<?php
namespace App\Http\Controllers\DesignPattern\Strategy;

use App\Traits\ApiResponser;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Strategy\Sorting\SortingStrategyContext;

class StrategyController extends Controller
{
    use ApiResponser;
    public function sortingTest(Request $request)
    {
        $items = [5, 3, 2, 4, 1];

        $sortingstrategycontext = new SortingStrategyContext('quicksort');
        $sortedItems = $sortingstrategycontext->sort($items);

        return $this->set_response($sortedItems, 200,'success', ['Sorting!']);
    }
}
SortingStrategy.php
<?php

namespace App\Strategy\Sorting;

interface SortingStrategy
{
    public function sort(array $items): array;
}

SortingStrategyContext.php
<?php

namespace App\Strategy\Sorting;

use App\Strategy\Sorting\SortingStrategy;
use App\Strategy\Sorting\BubbleSortStrategy;
use App\Strategy\Sorting\QuickSortStrategy;

class SortingStrategyContext
{
    private SortingStrategy $strategy;

    public function __construct( string $sortingStrategy )
    {
        switch ($sortingStrategy) {
            case 'bubblesort':
                $this->strategy = new BubbleSortStrategy();
                break;
            case 'quicksort':
                $this->strategy = new QuickSortStrategy();
                break;
            default:
                $this->strategy = new QuickSortStrategy();
                break;
        }
    }

    public function sort($items)
    {
        return $this->strategy->sort($items);
    }
}
BubbleSortStrategy.php
<?php

namespace App\Strategy\Sorting;

use App\Strategy\Sorting\SortingStrategy;

class BubbleSortStrategy implements SortingStrategy
{
    public function sort(array $items): array
    {
        $count = count($items);
        for ($i = 0; $i < $count; $i++) {
            for ($j = 0; $j < $count - $i - 1; $j++) {
                if ($items[$j] > $items[$j + 1]) {
                    $temp = $items[$j];
                    $items[$j] = $items[$j + 1];
                    $items[$j + 1] = $temp;
                }
            }
        }
        return $items;
    }
}
QuickSortStrategy.php
<?php

namespace App\Strategy\Sorting;

use App\Strategy\Sorting\SortingStrategy;

class QuickSortStrategy implements SortingStrategy
{
    public function sort(array $items): array
    {
        if (count($items) <= 1) {
            return $items;
        }

        $pivot = array_shift($items);
        $left = $right = array();
        foreach ($items as $item) {
            if ($item < $pivot) {
                $left[] = $item;
            } else {
                $right[] = $item;
            }
        }

        return array_merge($this->sort($left), array($pivot), $this->sort($right));
    }
}

Repository Design Pattern in laravel

in UnitController.php controller
<?php

namespace App\Http\Controllers\General;

use App\Contracts\General\UnitInterface;
use App\Traits\ApiResponser;
use App\Http\Controllers\Controller;

class UnitController extends Controller
{
    use ApiResponser;

    protected $unit;

    public function __construct(UnitInterface $unit)
    {
        $this->unit = $unit;
    }

    public function unitList()
    {
        $units = $this->unit->all();
        return $this->set_response(['units' => $units],  200, 'success', ['Unit list']);
    }
    
}

in UnitInterface.php interface
<?php
namespace App\Contracts\General;
interface UnitInterface
{
    public function all();
}

in UnitRepository.php repository
<?php
namespace App\Repositories\General;
use App\Models\General\Unit;
use App\Contracts\General\UnitInterface;

class UnitRepository implements UnitInterface
{
    public function all()
    {
        return Unit::all();
    }
}

in RepositoriesServiceProvider.php a custom service provider binding Interface & Concrete class (Repository)
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;

class RepositoriesServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind('App\Contracts\General\UnitInterface', 'App\Repositories\General\UnitRepository');
    }
}

in app.php
<?php
return [
    'providers' => [
        // Custom Service Providers...
        App\Providers\RepositoriesServiceProvider::class,
    ],
];

Upvotes: 2

Tharaka Dilshan
Tharaka Dilshan

Reputation: 4499

You don't have to consider that much about design patterns if you follow 'Laravel' pre-defined way. they kinda have defined almost everything by following those design patterns.

You can refer these articles as a start.

https://github.com/alexeymezenin/laravel-best-practices

https://www.innofied.com/top-10-laravel-best-practices/

And most importantly Official documentation. https://laravel.com/docs/7.x

The most import thing you need to consider when using 'Laravel' try to use 'Laravel' as much as possible. (Instead of pure php)

Upvotes: 3

Related Questions