Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Repository Pattern (Laravel)
// Interface/Contract
interface OrderRepositoryInterface {
  public function getAll();
  public function find($id);
}

class DbOrderRepository implements OrderRepositoryInterface {

  public function getAll()
  {
    // return Order::all();
    retuen Order::where('name', 'Rishabh')->order('created_at')->limit();
  }

  public function find($id)
  {
    return Order::findOrFail($id);
  }
  
}

class OrdersController extends Controller {

  protected $order;

  public function __construct(OrderRepositoryInterface $order)
  {
    $this->order = $order;
  }

  public function index()
  {
    $order = $this->order->find($id);

    view('orders.index', compact('orders'));
  }

}




// In Laravel

// App::bind(Contract, Implementation)
App::bind('OrderRepositoryInterface', 'DbOrderRepositoryInterface')

A Model is replaced by a Repository (that uses a Model or Entity in itself). This helps testing the controllers better as a custom mock implementaiton of the repository can be passed.

Testability (and probably further separation of concerns/external|decoupled API stuff) are the benefits.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment