grabbee
@grabbee

Стоит ли выносить получение ORM EntityManager в __constructor?

Стоит ли выносить получение ORM EntityManager в контроллере в __constructor ?

Вот пример кода, большая часть которого дублируется(часть стандартного CRUD). Раньше я выносил подобные куски в конструктор. А как правильно сделать такое в симфони?

public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ApiBundle:Upload')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Upload entity.');
        }
        //... 
    }

    /**
     * Displays a form to edit an existing Upload entity. 
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ApiBundle:Upload')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Upload entity.');
        }
        //... 
    }


Как правильно оптимизировать такое?

Я попробовал импортировать зависимость через сервисы, но как выяснилось так нельзя делать, если контроллер наследован от Symfony\Bundle\FrameworkBundle\Controller\Controller (?)

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class PhotoController extends Controller
{ 
    public function __construct(EntityManager $entityManager)
    {
        //...
    }


src/ApiBundle/Resources/config/services.yml
services:
    api.manager:
      class:  ApiBundle\Controller\PhotoController 
      arguments: [ @doctrine.orm.entity_manager ]


Catchable Fatal Error: Argument 1 passed to ApiBundle\Controller\PhotoController::__construct() must be an instance of Doctrine\ORM\EntityManager, none given, called in ...

Property Injection наверное не самое элегантное решение
symfony.com/doc/current/components/dependency_inje...

There are mainly only disadvantages to using property injection, it is similar to setter injection but with these additional important problems:

You cannot control when the dependency is set at all, it can be changed at any point in the object's lifetime.
You cannot use type hinting so you cannot be sure what dependency is injected except by writing into the class code to explicitly test the class instance before using it.

  • Вопрос задан
  • 468 просмотров
Решения вопроса 1
@bears
/**
 * @Route("/url/{id}")
 */
public function editAction(Upload $upload)
{
	...
}


Лучше так. Если сущность не найдется, то будет ошибка 404

symfony.com/doc/current/bundles/SensioFrameworkExt...
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
okwinza
@okwinza
PHP Developer
Еще можно использовать docs.sylius.org/en/latest/bundles/SyliusResourceBundle
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы