Created
June 23, 2019 03:22
-
-
Save shin1x1/f19efccde55e07a357ad7d4595cb976f to your computer and use it in GitHub Desktop.
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 Acme\Infrastructure\Repository; | |
use Acme\Domain\Exception\NotFoundException; | |
use Acme\Domain\Model\User; | |
use Acme\Domain\Model\UserId; | |
use Acme\Domain\Repository\UserRepository; | |
use Acme\Infrastructure\Eloquent\EloquentUser; | |
final class EloquentUserRepository implements UserRepository | |
{ | |
/** @var EloquentUser */ | |
private $eloquentUser; | |
/** | |
* @param EloquentUser $eloquentUser | |
*/ | |
public function __construct(EloquentUser $eloquentUser) | |
{ | |
$this->eloquentUser = $eloquentUser; | |
} | |
/** | |
* @param UserId $id | |
* @return User | |
* @throws NotFoundException | |
*/ | |
public function findById(UserId $id): User | |
{ | |
/** @var EloquentUser $eloquent */ | |
$eloquent = $this->eloquentUser->newQuery()->find($id->asInt()); | |
// you can use Facade | |
// $eloquent = EloquentUser::find($id->asInt()); | |
if ($eloquent === null) { | |
throw new NotFoundException('user not found:' . $id); | |
} | |
return new User( | |
new UserId($eloquent->id), | |
$eloquent->name, | |
$eloquent->email | |
); | |
} | |
/** | |
* @param User $user | |
* @return UserId | |
*/ | |
public function store(User $user): UserId | |
{ | |
if ($user->hasId()) { | |
$eloquent = $this->eloquentUser->newQuery()->findOrFail($user->getId()->asInt()); | |
} else { | |
$eloquent = $this->eloquentUser->newInstance(); | |
} | |
$eloquent->name = $user->getName(); | |
$eloquent->email = $user->getEmail(); | |
$eloquent->save(); | |
return new UserId($eloquent->id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment