Advertisement
Guest User

Untitled

a guest
Jul 2nd, 2016
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.05 KB | None | 0 0
  1. <?php
  2.  
  3. interface UserRepository
  4. {
  5.     function add(User $user);
  6. }
  7.  
  8. ###############
  9.  
  10. class DoctrineUserRepository implements UserRepository
  11. {
  12.     private $doctrine;
  13.  
  14.     public function __construct(Registry $doctrine)
  15.     {
  16.         $this->doctrine = $doctrine;
  17.     }
  18.  
  19.     function add(User $user)
  20.     {
  21.         $this->doctrine->getEntityManager()->getConnection()->beginTransaction();
  22.  
  23.         try{
  24.             $this->doctrine->getEntityManager()->persist($user);
  25.             $this->doctrine->getEntityManager()->flush();
  26.             $this->doctrine->getEntityManager()->commit();
  27.         } catch(\Exception $e){
  28.             $this->doctrine->getEntityManager()->rollback();
  29.             $this->doctrine->getEntityManager()->close();
  30.  
  31.             throw $e;
  32.         }
  33.     }
  34. }
  35.  
  36. ###############
  37.  
  38. class User
  39. {
  40.     private $username;
  41.  
  42.     private $password;
  43.  
  44.     public function __construct($username)
  45.     {
  46.         $this->username = $username;
  47.     }
  48.  
  49.     public static function create(array $data)
  50.     {
  51.         $user = new User;
  52.         $user->username = $data['username'];
  53.         $user->password = $data['password'];
  54.  
  55.         return $user;
  56.     }
  57. }
  58.  
  59. #################
  60.  
  61.  
  62. interface UserFactory
  63. {
  64.     public function createUser(array $data);
  65. }
  66.  
  67. class SecuredPasswordUserFactory implements UserFactory
  68. {
  69.     public function createUser(array $data)
  70.     {
  71.         $user = new User($data['username']);
  72.         $user->setPassword(md5($data['password']));
  73.  
  74.         return $user;
  75.     }
  76. }
  77.  
  78. ################
  79.  
  80.  
  81. class RegistrationService
  82. {
  83.     private $users;
  84.  
  85.     private $userFactory;
  86.  
  87.     public function __construct(UserRepository $users, UserFactory $factory)
  88.     {
  89.         $this->users = $users;
  90.         $this->userFactory = $factory;
  91.     }
  92.  
  93.     public function register(array $data)
  94.     {
  95.         $user = $this->userFactory->createUser($data);
  96.  
  97.         try {
  98.             $this->users->add($user);
  99.         } catch (\Exception $e) {
  100.             return false;
  101.         }
  102.  
  103.         return true;
  104.     }
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement