Zend Framewok 2, Doctrine 2 and where business logic fits in

Note that I want to save the user in the database, my action is to add the following:

public function addAction() { $form = new UserForm(); $form->get('submit')->setValue('Add'); $request = $this->getRequest(); if ($request->isPost()) { $userFilter = new UserFilter(); $form->setInputFilter( $userFilter->getInputFilter() ); $form->setData( $request->getPost() ); if ($form->isValid()) $user = new User(); $user->setEmail($form->getInputFilter()->getValue('email') ); $user->setNome( $form->getInputFilter()->getValue('name') ); $em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); $em->persist($user); $em->flush(); return $this->redirect()->toRoute('user'); } } return array('form' => $form); } 

It is very simple to save the user in the database, however, if I need to add complex business logic, I want to check if the email is unique and that I also want to access some web service to check if the answer to the final question is about life, the universe, and everything is really 42, and if this is true, I want to save the user in the database if I do not want to show the message to the user.

You can add an action, but, as I was told, this is not a good practice, I can put this business logic inside the User object, but it will add a connection between zf2 and the doctrine with the entity, and this is also Bad. Searching the Internet for a solution to the answer seemed to put business logic in the Service Layer.

By deploying the Service Layer solution, you can create the UserBusinessLogic class and create a save method that will execute the business logic and save the user, if everything is in order.

Does this sound right? Is there any documentation on this? Perhaps a code example showing how to handle business logic using doctrine 2 and zf2 and services.

I think the bottom line is this: what is the best practice of where to put the business logic when using zf2 and doctrine 2?

Assuming a service solution is the best way. If I have Entitys Users, Groups and the connection between the two, I would create a service called "access", and this service will be the one who receives data from the controllers for saving users by groups, binds them 2, and also performs any other task , for example, sending mail to reset the user password. Does this sound right?

+7
source share
1 answer

You have the right idea. To disable Doctrine 2, you can create another layer that follows one of the interfaces in Zend \ Db but uses Doctrine to interact with the database.

In addition, for validation, you can create your own input filters for a form that validates the database using Doctrine.

The idea is that everything behind the service can be replaced by changing the service, as long as the method names remain unchanged. That way, you might later replace Doctrine with Propel, and you won’t have to reorganize your controllers and views, just a class of service.

+1
source

All Articles