Skip to content

Instantly share code, notes, and snippets.

@cherifGsoul
Last active October 12, 2017 22:22
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 cherifGsoul/4f4eacaf3de08fd3308e06dafd74bf30 to your computer and use it in GitHub Desktop.
Save cherifGsoul/4f4eacaf3de08fd3308e06dafd74bf30 to your computer and use it in GitHub Desktop.
Quick example of repository pattern using Yii2 active record
<?php
namespace Todolist\Infrastructure\Persistence\Yii\Respository;
use Todolist\Domain\Model\Todo\Todo;
use Todolist\Domain\Model\Todo\TodoRepository;
use Todolist\Infrastructure\Persistence\Yii\Record\TodoRecord;
class TodoActiveRepository implements TodoRepository
{
public function forId(TodoId $id)
{
//assuming $id has __toString so it can be casted to string automaticaly
$record = TodoRecord::find()->where([ 'id' => $id ])->one();
$todo = $this->fromRecord($record);
return $todo;
}
public function add(Todo $todo)
{
$record = $this->toRecord($todo);
return $record->save(false); // false beacause domain model should be in valid state dosent need to be validated
}
public function nextIdentity()
{
return TodoId::generate();
}
/**
* can have its own class TodoAdapter
*/
private funcion fromRecord(TodoRecord $record)
{
return new Todo(TodoId::fromString($record->id),
TodoName::fromString($record->name),
Assignee::fromString($record->assignee_id),
DueDate::fromFormat($record->due_date, 'Y-m-d')
);
}
/**
* can have its own class TodoAdapter
*/
private function toRecord(Todo $todo)
{
$record = new TodoRecord();
$record->setAttributes([
'id' => (string)$todo->getId(),
'name' => (string)$todo->getName(),
'assignee_id' => (string)$todo->getAssignee(),
'due_date' => (string)$todo->getDueDate()->toFormat('Y-m-d')
]);
return $record;
}
}
<?php
namespace Todolist\Domain\Model\Todo;
interface TodoRepository
{
/**
* fetch a todo by its TodoId
*/
public function forId(TodoId $id);
public function add(Todo $todo);
/**
* generate a TodoId
* assuming that a Todo is not an autoincrement but an Uuid
*/
public function nextIdentity();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment