Skip to content

Instantly share code, notes, and snippets.

@shin1x1
Created June 23, 2019 03: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 shin1x1/f19efccde55e07a357ad7d4595cb976f to your computer and use it in GitHub Desktop.
Save shin1x1/f19efccde55e07a357ad7d4595cb976f to your computer and use it in GitHub Desktop.
<?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