Last active
December 25, 2015 01:29
-
-
Save dadamssg/6895735 to your computer and use it in GitHub Desktop.
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 | |
/** Abstract Repository Class **/ | |
abstract class PostRepository { | |
public function create(array $input) | |
{ | |
$post = $this->_create($input); | |
if ($post) { | |
$post = $this->toJson($post); | |
Event::fire('post.created', array($post)); | |
} | |
return $post; | |
} | |
public function findById($id) | |
{ | |
$post = $this->_findById($id); | |
if ($post) { | |
$post = $this->toJson($post); | |
Event::fire('post.found', array($post)); | |
} | |
return $post; | |
} | |
public function getLatest($limit) | |
{ | |
$posts = $this->_getLatest($limit); | |
if ($posts) { | |
$posts = $this->toJson($posts); | |
Event::fire('posts.latest', array($posts)); | |
} | |
return $this->toJson($posts); | |
} | |
public function destroy($id) | |
{ | |
if ($this->_destory($id)) { | |
Event::fire('post.destroy', array($id)); | |
return true; | |
} | |
return false; | |
} | |
abstract protected function _create(array $input); | |
abstract protected function _findById($id); | |
abstract protected function _getLatest($limit); | |
abstract protected function _destroy($id); | |
abstract public function toJson($obj); | |
} | |
/** Eloquent Repository Implementation **/ | |
class EloquentPostRepository extends PostRepository { | |
protected function _create(array $input) | |
{ | |
return Post::create($input); | |
} | |
protected function _findById($id) | |
{ | |
return Post::find($id); | |
} | |
protected function _getLatest($limit) | |
{ | |
return Post::orderBy('created_at')->take($limit)->get(); | |
} | |
protected function _destroy($id) | |
{ | |
return Post::find($id)->delete(); | |
} | |
public function toJson($obj) | |
{ | |
if (is_array($obj)) { | |
$array = []; | |
foreach ($obj as $model) { | |
if ($model instanceof Eloquent) { | |
$array[] = $model->toJson(); | |
} | |
} | |
return $array; | |
} elseif ($obj instanceof Eloquent) { | |
return $obj->toJson(); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment