Last active
August 29, 2015 13:57
-
-
Save lukemorton/9566636 to your computer and use it in GitHub Desktop.
Vision of controller future
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
module App | |
class PostController | |
include DependencyHelper # Include #inject | |
include TemplateEngineHelper # Includes #render | |
include ResponseHelper # Includes #redirect | |
inject_methods [:create_post, :post_model, :post_view, :validation_exception] | |
def initialize(config) | |
inject(config) | |
end | |
def create(request) | |
post = (request[:post][:post] || {}) | |
render('post/new', :post => post, :errors => request[:errors]) | |
end | |
def create_process(request) | |
begin | |
post_id = create_post.exec(:post => request[:post][:post]) | |
redirect("/post/#{post_id}").merge(:flash => "Post created!") | |
rescue e => validation_exception | |
create(request.merge(:errors => e.errors)) | |
end | |
end | |
def view(request) | |
post = post_model.build(:post_id => request[:params][:post_id]) | |
render('post/view', post_view.build(:post => post)) | |
end | |
end | |
end |
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; | |
class PostController | |
{ | |
use DependencyHelper; // Includes ::inject() | |
use TemplateEngineHelper; // Includes ::render() | |
use ResponseHelper; // Includes ::redirect() | |
use ArrayHelper; // Includes ::arr_get() | |
private $post_model; | |
private $post_view; | |
private $create_post; | |
public function __construct($config) | |
{ | |
$this->inject($config); | |
} | |
public function create($request) | |
{ | |
$post = $this->arr_get($request, 'post.post', []); | |
$errors = $this->arr_get($request, 'errors', []); | |
return $this->render('post/new', compact('post', 'errors')); | |
} | |
public function create_process($request) | |
{ | |
try | |
{ | |
$post = $this->arr_get($request, 'post.post'); | |
$post_id = $this->create_post->exec(compact('post')); | |
return $this->redirect("/post/{$post_id}") + ['flash' => 'Post created!']; | |
} | |
catch (ValidationException $e) | |
{ | |
return $this->create($request + ['errors' => $e->errors()]); | |
} | |
} | |
public function view($request) | |
{ | |
$post_id = $this->arr_get($request, 'params.id'); | |
$post = $this->post_model->build(compact('post_id')); | |
return $this->render('post/view', $this->post_view->build(compact('post'))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment