GitHub Repository

apiato

Definition

Criterias are classes used to hold and apply query condition when retrieving data from the database through a Repository.

Without using a Criteria class, you can add your query conditions to a Repository or to a Model as scope. But with Criterias, your query conditions can be shared across multiple Models and Repositories. It allows you to define the query condition once and use it anywhere in the App.

Principles

Rules

Folder Structure

 - app
    - Containers
        - {container-name}
            - Data
                - Criterias
                  - ColourRedCriteria.php
                  - RaceCarsCriteria.php
                  - ...
    - Ship
        - Features
            - Criterias
               - Eloquent
                  - CreatedTodayCriteria.php
                  - NotNullCriteria.php
                  - ...

Code Samples

Example: a shared Criteria

<?php

namespace App\Ship\Features\Criterias\Eloquent;

use App\Ship\Parents\Criterias\Criteria;
use Prettus\Repository\Contracts\RepositoryInterface as PrettusRepositoryInterface;

class OrderByCreationDateDescendingCriteria extends Criteria
{
    public function apply($model, PrettusRepositoryInterface $repository)
    {
        return $model->orderBy('created_at', 'desc');
    }
}

Usage from Task:

<?php

public function run()
{
    $this->userRepository->pushCriteria(new OrderByCreationDateDescendingCriteria);

    $users = $this->userRepository->paginate();

    return $users;
}

Example: Criteria accepting data input:

<?php

namespace App\Ship\Features\Criterias\Eloquent;

use App\Ship\Parents\Criterias\Criteria;
use Prettus\Repository\Contracts\RepositoryInterface as PrettusRepositoryInterface;

class ThisUserCriteria extends Criteria
{

    private $userId;

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

    public function apply($model, PrettusRepositoryInterface $repository)
    {
        return $model->where('user_id', '=', $this->userId);
    }
}

Example: Passing data from Task to Criteria:

<?php

public function run($user)
{
    $this->accountRepository->pushCriteria(new ThisUserCriteria($user->id));

    $accounts = $this->accountRepository->paginate();

    return $accounts;
}

For more information about the Criteria read this.