Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save netlooker/85a34d2f8919e3eebf33143e4e00deea to your computer and use it in GitHub Desktop.
Save netlooker/85a34d2f8919e3eebf33143e4e00deea to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace Cocoders\core\Application\UseCase;
use Cocoders\Core\Domain\Users;
use Cocoders\Core\Application\TransactionManager;
use Cocoders\core\Application\UseCase\RegisterUser\UserFactory;
use Cocoders\core\Application\UseCase\RegisterUser\Command;
class RegisterUser
{
private $transactionManager;
private $users;
private $factory;
public function __construct(TransactionManager $manager, Users $users, UserFactory $factory)
{
$this->transactionManager = $manager;
$this->users = $users;
$this->factory = $factory;
}
public function execute(Command $command): void
{
$this->transactionManager->begin();
try {
$this->users->add(
$this->factory->create($user)
);
$this->transactionManager->commit();
} catch (\Throwable $t) {
$this->transactionManager->rollback();
throw $t;
}
}
}
<?php
declare(strict_types=1);
namespace Cocoders\Core\Domain;
class User
{
private $id;
private $username;
private $email;
private $userProfile;
public function __construct(UserId $id, string $username, Email $email, UserProfile $profile)
{
$this->id = $id;
$this->username = $username;
$this->email = $email;
$this->profile = $profile;
}
}
<?php
declare(strict_types=1);
namespace Cocoders\Core\Domain;
use Cocoders\Core\Domain\Exception\UserNotFound;
interface Users
{
public function add(User $user): void;
/**
* @throws UserNotFound
*/
public function get(UserId $userId): User;
}
<?php
declare(strict_types=1);
namespace Cocoders\Integration\Core\Domain;
use Cocoders\Core\Domain\Exception\UserNotFound;
use Cocoders\Core\Domain\User;
use Doctrine\Common\Persistence\ObjectManager;
final class Users
{
private $manager;
public function __construct(ObjectManager $manager)
{
$this->manager = $manager;
}
public function add(User $user): void
{
$this->manager->persist($user);
}
public function get(UserId $userId): User
{
$user = $this->manager->getRepository(User::class)->find((string) $userId);
if (!$user) {
throw new UserNotFound();
}
return $user;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment