Created
December 10, 2018 00:28
-
-
Save warrenca/5ece4c42089b5b12b4d9cd0cdbddce16 to your computer and use it in GitHub Desktop.
Laravel Repository Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use Warrenca\Laravel\Repositories\UserRepository; | |
/** | |
* Class CompanyUserController | |
*/ | |
class CompanyUserController extends Controller | |
{ | |
public function index($companyId) | |
{ | |
$userRepository = new UserRepository(new User); | |
$users = $userRepository->getActiveUserByCompany($companyId); | |
return view('user.listings', compact('users')); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Warrenca\Laravel\Repositories; | |
use Illuminate\Database\Eloquent\Model; | |
/** | |
* Interface ModelServiceInterface | |
*/ | |
interface ModelRepositoryInterface | |
{ | |
public function setModel(Model $model); | |
public function getModel(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Warrenca\Laravel\Services; | |
use Illuminate\Database\Eloquent\Model; | |
/** | |
* Trait EntityServiceTraits | |
*/ | |
trait ModelRepositoryTraits | |
{ | |
/** | |
* @param Model $model | |
* @return Model | |
*/ | |
public function setModel(Model $model) | |
{ | |
abort_unless($this->modelClass === get_class($model), 500); | |
$this->model = $model; | |
return $this; | |
} | |
/** | |
* @return Model | |
*/ | |
public function getModel() | |
{ | |
return $this->model; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Warrenca\Laravel\Repositories; | |
use Warrenca\Laravel\Models\User; | |
/** | |
* Class User | |
*/ | |
class UserRepository extends Model implements ModelRepositoryInterface | |
{ | |
protected $modelClass = User::class; | |
use ModelRepositoryTraits; | |
public function __construct(User $user = null) | |
{ | |
$this->model = $user; | |
} | |
public function getActiveUserByCompany($companyId) | |
{ | |
return $this-model->whereIsActive(1)->whereCompanyId($companyId)->get(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment