Controller cleaning. Doctrine in the model

I want to make my controller thin and separate the business logic from other operations. For example, I have an action:

public function indexAction()
{
    $languages = $this  ->getEntityManager()
                        ->getRepository('\ApanelLanguage\Entity\LanguageCommon')
                        ->getLanguagesList();
    $viewModel = new ViewModel(['languages' => $languages]);
    return $viewModel; 
}

but I want to get the following:

public function indexAction()
{
    $model = $new LanguageModel();
    $model->getLanguagesList();
    return $viewModel; 
}

Can this be done? What do I need in Language / Model / LanguageModel? Thanks you

+4
source share
1 answer

Removing business logic from your controller is a great idea for code reuse and maintainability; however, I would recommend not shifting the logic to your models. A better solution would be to add a service level to your application.

What is the level of service? Martin Fowler describes this as the following :

[ ] , .

, .

, - . - .

"" API, :

interface ServiceInterface
{
    public function setObjectManager($objectManager);

    public function setRepository($respository);

    public function find($id);

    public function fetchRow($criteria);

    public function fetchAll($criteria);

    public function insert($object);

    public function update($object);

    public function delete($object);
}

"LanguageService".

class LanguageService implements ServiceInterface
{
  // ... all methods from interface

    public function getLanguageList()        
    {
       return $this->repository->getLanguagesList();
    }
}

,

class FooController extends AbstractActionController
{
    protected $languageService;

    public function __construct(ServiceInterface $languageService)
    {
        $this->languageService = $languageService;
    }

    public function indexAction()
    {
        $languages = $this->languageService->getLanguageList();

        $viewModel = new ViewModel(['languages' => $languages]);

        return $viewModel;
    }

    public function insertAction()
    {
        $request = $this->getRequest();
        $service = $this->languageService;

        $form = $service->getInsertForm();

        if ($request->isPost()) {
            $form->setData($request->getPost());

            if ($form->isValid()) {

                // if our form used the DoctrineObjectHydrator
                // we will get a entity back populated with the
                // form data
                $language = $service->insert($form->getData());

                if ($language instanceof Entity\Language) {
                    // success
                } else {
                    // failure
                }
            }
        }
        //
    }


}
+4

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


All Articles