Skip to content

Instantly share code, notes, and snippets.

@denjin
Last active May 16, 2017 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save denjin/b7fd765e2e98154a627b to your computer and use it in GitHub Desktop.
Save denjin/b7fd765e2e98154a627b to your computer and use it in GitHub Desktop.
<?php
use Presenters\Presenter;
use Presenters\PostPresenter;
use Repositories\Posts\PostRepository as Post;
class PostController extends BaseController {
protected $post;
protected $presenter;
public function __construct(Post $post, Presenter $presenter) {
//injected services
$this->post = $post;
$this->presenter = $presenter;
}
public function show($slug) {
$post = $this->post->findByKey('slug', $slug);
if($post) {
$post = $this->presenter->model($post, new PostPresenter);
return View::make('posts.single', compact('post'));
}
App::abort(404);
}
}
<?php namespace Presenters;
use ArrayAccess;
abstract class BasePresenter implements ArrayAccess {
//the object to present
protected $object;
//Inject the object to be presented
public function set($object) {
$this->object = $object;
}
//Checks to see if the offset exists on the current object
public function offsetExists($key) {
return isset($this->object[$key]);
}
//Retrieve the key from the object as if it were an array (square brackets)
public function offsetGet($key) {
return $this->__get($key);
}
//Set the key of an object as if it were an array
public function offsetSet($key, $value) {
$this->object[$key] = $value;
}
//Unset the key of an object as if it were an array
public function offsetUnset($key) {
unset($this->object[$key]);
}
//Check to see if there's a method on the presenter, else pass through to the object
public function __get($key) {
if(method_exists($this, $key)) {
return $this->{$key}();
}
return $this->object->$key;
}
//formats the date_time fields auto-created by laravel
public function created_at() {
return $this->object->created_at->format('dS M Y \a\t G:i');
}
public function updated_at() {
return $this->object->updated_at->format('dS M Y \a\t G:i');
}
}
<?php namespace Presenters;
class Presenter {
//Returns an instance of a model, wrapped in a presenter
public function model(Model $model, Presentable $presenter) {
$object = clone $presenter;
$object->set($model);
return $object;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment