Javan Cipta Solusi
Published in

Javan Cipta Solusi

Laravel Repository Pattern (Hopefully) the Right Way

Laravel Repository Pattern

Tentang Repository Pattern

class Tweet extends Eloquent {
protected $fillable = [‘tweet’, ‘user_id’];
public function user()
{
return $this->belongsTo(‘App\User’, ‘user_id’);
}
}
class UserController extends Controller {
public function getTweets(Request $request) {
$user = User::find($request->user_id);
$latestTweets = Tweet::where('user_id', $user->id)->orderBy('created_at', 'desc');
}
}
class TweetRepository {
protected $model;
public function __construct(Tweet $tweet) {
$this->model = $tweet;
}
public function getLatestTweets($userId) {
return $this->model->where('user_id', $userId)->orderBy('created_at', 'desc');
}
}
class UserController extends Controller {
protected $tweetRepository;
public function __construct(TweetRepository $tweetRepository) {
$this->tweetRepository = $tweetRepository;
}
public function getTweets(Request $request) {
$user = User::find($request->user_id);
$latestTweets = $this->tweetRepository->getLatestTweets($user->id);
}
}

Trus gimana kalau butuh logic sebelum interaksi ke database?

class TweetService
{
protected $tweetRepository;
public function __construct(TweetRepository $tweetRepository)
{
$this->tweetRepository = $tweetRepository;
}
public function getTweets($userId)
{
return $this->tweetRepository->getLatestTweets($userId);
}
}

Contoh kasus lain penggunaan Repository Pattern

class TweetRepository {
public function getLatestTweets($userId) {
return [[
'id' => 1,
'tweet' => 'sip',
'user_id' => 1,
'created_at' => null,
'updated_at' => null
]];
}
}

--

--

Business Process Optimization Partner. Contact us to help you optimize your business using technology.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store