Repositories and Interfaces in Laravel

We use model, views, and controllers in normal projects but in some project, we use interfaces and repositories also. We rarely use them because these have different usage requirements. Interfaces are used in the general OOP to describe which methods the class that implements the interface is offering regardless of the actual implementation. Interfaces separate the service from the actual implementation.

<?php


namespace App\Orders;


class OrdersCache

{


    protected $cache;


    public function __construct(\SomePackage\Cache\Memcached $cache)

    {

        $this->cache = $cache;

    }



    public function find($id)

    {

        if ($this->cache->has($id))    {

            //

        }

    }

}

?>

In the above example, the code is tightly coupled with the cache implementation so when the cache class changes the code must also be changed accordingly. Instead of changing the code could depend on an interface that is unconvinced of the implementation.

<?php


namespace App\Orders;


use Illuminate\Contracts\Cache\Repository as Cache;


class OrdersCache

{


    public function __construct(Cache $cache)

    {

        $this->cache = $cache;

    }



    public function find($id)

    {

        if ($this->cache->has($id))    {

            //

        }

    }

}

?>

Repositories

Repository pattern is a type of container where data access logic is stored. It hides the details of data access logic from business logic.  It separates the data access logic and maps it to the entities in the business logic. Communication between data access logic and business logic is done through the interface. It separates the business logic from interactions with an underlying data source or web service. This separation has some benefits. It centralizes the data logic. Provides a substitution point for unit tests. Provides a flexible architecture that can be adapted as the overall design of the application.