W
W
why72017-01-25 22:44:08
symfony
why7, 2017-01-25 22:44:08

How to do it right from the point of view of OOP and common sense?

You need to activate your user account.
There is a user entity, with an activation method:

user entity

class User
{
    private $is_active = false;

    public function activate(string $activation_token) : void
    {
        if ($activation_token !== $this->getActivationToken()) {
            throw new UserActivationFailException();
        }

        $this->is_active = true;
    }

    public function getActivationToken() : string
    {
        //генерация ключа активации
    }
}


And the activation implementation:
controller action

public function completeSignUpAction(Request $request) : Response
{
    $email = mb_strtolower(trim($request->get('email')), 'UTF-8');
    $activation_token = trim($request->get('token'));

    //валидация

    $entity_manager = $this->getDoctrine()->getManager();

    try {
        //ну или в контейнер можно положить
        (new UserActivator($entity_manager))->activate($email, $activation_token);

    } catch (UserActivationFailException $e) {

        throw new NotFoundHttpException();
    }

    return new RedirectResponse($this->generateUrl('login'));
}


UserActivator

class UserActivator
{
    private $entity_manager;

    public function __construct(EntityManager $entity_manager)
    {
        $this->entity_manager = $entity_manager;
    }

    public function activate(string $email, string $activation_token) : void
    {
        //проверка входных данных

        $user_repository = $this->entity_manager->getRepository(User::class);

        $user = $user_repository->findOneBy(['email' => $email]);

        if (is_null($user)) {
            throw new UserActivationFailException();
        }

        $user->activate($activation_token);
        $this->entity_manager->flush($user);
    }
}


Logically, the User entity is responsible for activating a particular account. she has enough data for this.
But if I understand correctly, then the entity should not have access to its repository. And in order to save changes to the database, you need to wrap the activation in a service and transfer the dependencies necessary for saving to the database to it. Or did I misunderstand?
Is it right to make services like UserActivator and won't there be a big growth of such classes if after changing the state the entity needs to save the changes to the database?
In general, how to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
heartdevil, 2017-01-26
@why7

I won’t say for the symphony, but yes. Everything is exactly as you described. Inject repository dependencies into services, inject services into controllers, and work with services in controller actions. There can be a lot of different services.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question