How to handle exceptions when checking Doctrine 2

I am new to Doctrine 2 (and exceptions in PHP, really), but I'm trying to come up with a reliable check mechanism for Doctrine 2 (on top of CodeIgniter) by following this page .

I'm currently wondering where I would define the ValidateException class and how to “try” to persist (persist?) On my entity (from the controller, library, etc.).

I would like to have something where after that (e.g. in the authentication library):

$user->username = $username;
$user->email_address = $email_address;
$user->password = $password;

$em->persist($user);
$em->flush();

return $foo; //where $foo refers to whether $em->flush() worked...

I could simply return whether this perseverance was successful (i.e., passed validation and retention) or was not successful (i.e. failed verification).

+3
1

, Factory. , ( POST) User. User ( ). / , ( ).

class UserFactory
{
  /** @var Doctrine Entity Manager */
  private $_em;

  function __construct(EntityManager $em) {
    $this->_em = $em;
  }

  function createUserFromArray($data) {
    $user = new User();
    $user->setUsername($data['username']);
    $user->setEmail($data['email']);

    $this->_em->persist($user);
    $this->_em->flush(); // Or this could be called from some other place

    return $user;
  }
}

, , :

// Get the EntityManger from wherever (registry, session, etc)
$userFactory = new UserFactory($em);
$user = $userFactory->createFromArray($dataFromForm);

.

-, getters ( ), , .

User:

function setEmail($email) {
  // Do some validations on the email address
  if (!is_valid_email($email)) {
    throw new Exception('Invalid Email');
  }
  $this->email = $email;
}

-, , , , - . , / Model/Entity.

class User
{
  /** @PrePersist @PreUpdate */
  function ensureUniqueEmail()
  {
    // Do your check, else throw exception
  }
}
+4

Source: https://habr.com/ru/post/1763290/


All Articles