Skip to content

Instantly share code, notes, and snippets.

Created September 18, 2014 23:41
Show Gist options
  • Save anonymous/dbba88d76158320661c5 to your computer and use it in GitHub Desktop.
Save anonymous/dbba88d76158320661c5 to your computer and use it in GitHub Desktop.
<?php
class Blog
{
private $dataAccess;
public function __construct(PostDataAccess $dataAccess)
{
$this->dataAccess = $dataAccess;
}
public function createPost($title, $body)
{
$post = new Post($title, $body);
$this->dataAccess->save($post);
return $post;
}
}
<?php
class PdoPostDataAccess implements PostDataAccess
{
private $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function save(Post $post)
{
$statement = $this->pdo->prepare('INSERT INTO posts (title, body) VALUES (:title, :body)');
$statement->bindParam('title', $post->getTitle(), PDO::PARAM_STR);
$statement->bindParam('body', $post->getBody(), PDO::PARAM_STR);
$statement->execute();
$post->setId($this->pdo->lastInsertId());
}
}
<?php
class Post
{
private $id;
private $title;
private $body;
public function __construct($title, $body)
{
$this->title = $title;
$this->body = $body;
}
public function setId($value)
{
$this->id = $value;
}
public function getId()
{
return $this->id;
}
public function getTitle()
{
return $this->title;
}
public function getBody()
{
return $this->body;
}
}
<?php
interface PostDataAccess
{
public function save(Post $post);
}
<?php
require __DIR__ . '/Blog.php';
require __DIR__ . '/Post.php';
require __DIR__ . '/PostDataAccess.php';
require __DIR__ . '/PdoPostDataAccess.php';
$blog = new Blog(new PdoPostDataAccess(new PDO('mysql:host=localhost;dbname=blog;charset=utf8', 'root', 'root')));
$post = $blog->createPost('New post', 'New post text body');
var_dump($post);
/**
* Output:
*
* class Post#4 (3)
* {
* private $id => string(1) "1"
* private $title => string(8) "New post"
* private $body => string(18) "New post text body"
* }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment