Skip to content

Instantly share code, notes, and snippets.

@BernhardPosselt
Last active December 14, 2015 03:28
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 BernhardPosselt/5020760 to your computer and use it in GitHub Desktop.
Save BernhardPosselt/5020760 to your computer and use it in GitHub Desktop.
Simple controller
<?php
require __DIR__ . '/autoloader.php';
// without Pimple
$route = new Route();
$route->add('/blog/.+/.+', function($ownerId, $postId) {
$db = new PDOSomething('user', 'pass', 'db'); // instantiate db
$mapper = new BlogPostMapper($db);
$controller = new BlogPostController($mapper);
echo $controller->view($ownerId, $postId);
});
$route->submit();
// with Pimple
$route = new Route();
$container = new Container();
$route->add('/blog/.+/.+', function($ownerId, $postId) {
$controller = $container['BlogPostController'];
echo $controller->view($ownerId, $postId);
});
$route->submit();
// in another file
class Container extends Pimple {
public function __construct(){
$this['DB'] = $this->share(function($c){
return new PDOSomething('user', 'pass', 'db');
});
$this['BlogPostMapper'] = function($c){
return new BlogPostMapper($c['DB']);
};
$this['BlogPostController'] = function($c){
return new BlogPostController($c['BlogPostMapper']);
};
}
}
// in another file
class BlogPostController {
private $posts;
public function __construct($mapper){
$this->posts = $mapper;
}
public function show($ownerId, $postId){
// do your sql query and write it into the following vars
$post = $this->posts->find($ownerId, $postId);
$content = $post->content;
$title = $post->title;
$menu = array(
'entry1' => array(
'link' => '/blog/2',
'active' => true
),
);
// create template
$tpl = new h2o('index.html');
$args = array(
'title' => $title,
'content' => $content,
'menu' => $menu
);
return $h2o->render($args);
}
}
// in another file
class BlogPostMapper {
private $db;
public function __construct($db){
$this->db = $db;
}
public function find($ownerId, $postId){
$sql = 'SELECT * FROM posts WHERE owner = ? and id = ?';
$result = $db->execute($sql, array($ownerId, $postId);
$post = new Post();
while($row = $result->fetchRow()){
$post->title = $row['title'];
$post->content = $row['content'];
}
return $post;
}
public function delete($id){
$sql = 'DELETE FROM posts WHERE id = ?';
$db->execute($sql, array($id);
}
}
// in another file
class Post {
public $title;
public $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment