Skip to content

Instantly share code, notes, and snippets.

@victorknust
Created December 29, 2015 12:57
Show Gist options
  • Save victorknust/6b5deab551b2a6b5ad81 to your computer and use it in GitHub Desktop.
Save victorknust/6b5deab551b2a6b5ad81 to your computer and use it in GitHub Desktop.
<?php
/**
* Class Mapper
*/
abstract class Mapper
{
/**
* @var PDO
*/
private $connection;
/**
* @var
*/
protected $table;
/**
* @param PDO $connection
*/
public function __construct(PDO $connection)
{
$this->connection = $connection;
}
/**
* @param array $attributes
* @return Entity
*/
public static function createEntity(array $attributes)
{
return new Book($attributes);
}
/**
* @param Entity $entity
*/
public function insert(Entity $entity)
{
}
/**
* @param Entity $entity
*/
public function update(Entity $entity)
{
}
/**
* @param Entity $entity
*/
public function delete(Entity $entity)
{
}
/**
* @param array $condition
* @return Entity[]
*/
public function findAll(array $condition)
{
}
/**
* @param array $condition
* @return Entity
*/
public function findOne(array $condition)
{
}
}
/**
* Class BooksMapper
*/
class BooksMapper extends Mapper
{
/**
* @var string
*/
protected $table = 'books';
}
/**
* Class Entity
*/
abstract class Entity
{
/**
* @var array
*/
protected $attributes = [];
/**
* @param array $attributes
*/
public function __construct($attributes)
{
$this->import($attributes);
}
/**
* @param $attributes
*/
public function import($attributes)
{
$this->attributes = $attributes;
}
/**
* Returns data from entity
* @return array
*/
public function export()
{
return $this->attributes;
}
/**
* @param $name
* @return mixed
*/
public function __get($name)
{
return (isset($this->attributes[$name])) ? $this->attributes[$name] : null;
}
/**
* @param $name
* @param $value
*/
public function __set($name, $value)
{
$this->attributes[$name] = $value;
}
}
class Book extends Entity
{
}
/**
* Usage
*/
$booksMapper = new BooksMapper(new PDO('mysql:hostname=localhost;dbname=test', 'root', ''));
$book = BooksMapper::createEntity([
'title' => 'Test book',
'description' => 'Test book',
'author_id' => 15,
'status' => 2,
'date' => time()
]);
$booksMapper->insert($book);
$book->title = 'New title';
$booksMapper->update($book);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment