Last active
October 12, 2017 22:22
-
-
Save cherifGsoul/4f4eacaf3de08fd3308e06dafd74bf30 to your computer and use it in GitHub Desktop.
Quick example of repository pattern using Yii2 active record
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 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; | |
} | |
} |
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 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