Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AbstractRepository com um exemplo de UserRepostory
<?php namespace App\Repositories\Eloquent;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
abstract class AbstractRepository
{
protected $modelClass;
public function getAll($columns = ['*'])
{
$results = $this->newModel()->all($columns);
return $this->parseResults($results);
}
public function getAllPaginated($perPage = 15, $columns = ['*'])
{
$query = $this->newQuery();
$results = $query->paginate($perPage, $columns);
return $this->parseResults($results);
}
public function getById($id, $columns = ['*'])
{
$results = $this->newModel()->find($id, $columns);
return $this->parseResults($results);
}
public function create(array $attributes = [])
{
$model = $this->newModel();
$model->fill($attributes);
return $this->save($model);
}
public function save($model)
{
return $this->parseResults($model->save());
}
public function updateById($id, array $attributes)
{
$model = $this->newModel()->findOrFail($id);
$results = $model->update($attributes);
return $this->parseResults($results);
}
/**
* @return Model
* @throws \Exception
*/
protected function newModel()
{
$model = app($this->modelClass);
if (!$model instanceof Model) {
throw new \Exception("Class {$this->modelClass} must be an instance of Illuminate\\Database\\Eloquent\\Model");
}
return $model;
}
/**
* @return Builder
* @throws \Exception
*/
protected function newQuery()
{
return $this->newModel()->newQuery();
}
protected function parseResults($results)
{
return $results;
}
}
<?php
namespace App\Http\Controllers;
use App\Repositories\Eloquent\UserRepository;
class UserController extends Controller
{
protected $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function index()
{
return $this->userRepository->getAll();
}
public function show($id)
{
return $this->userRepository->find($id);
}
public function store(Request $request)
{
return $this->userRepository->create($request->all());
}
public function destroy($id)
{
return $this->userRepository->delete($id);
}
}
<?php namespace App\Repositories\Eloquent;
use App\Entities\User;
class UserRepository extends AbstractRepository
{
protected $modelClass = User::class;
//metodos personalizados aqui
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.