0

看看那个代码

<?php

namespace Sestante\SestanteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sestante\SestanteBundle\Model\StrutturaManager;

class MainController extends Controller
{
    public function indexAction(Request $request)
    {
        return $this->render('SestanteSestanteBundle:Main:index.html.twig');
    }

    public function showLodgingsAction(Request $request)
    {
        $repo = $this->getDoctrine()->getRepository('SestanteSestanteBundle:Struttura');
        $usr = $this->get('security.context')->getToken()->getUser();
        $usrId = $usr->getId();
        $sm = new StrutturaManager($repo);
        $lodgingList = $sm->retrieveLodgingsFromUser($usrId);
        return $this->render('SestanteSestanteBundle:Main:showLodgings.html.twig',array('lodgingList' => $lodgingList));
    }
}

这是我一直在编写的应用程序的控制器。

来看看showLodgingsAction。我已经尝试将所有业务逻辑放入StrutturaManager带有存储库的模型()中(我直接从控制器传递,因为据我所知,它们仅在此处或通过 DI 可用)查询我的数据库,做一些详细说明并返回我将呈现到模板上的列表。

第一个问题:这种“代码分离”是好的,还是存在更好的方法来做我想做的事情?

第二个问题:假设,现在,我想使用StrutturaManagerinto 类型的对象indexAction。请记住,我的对象需要一个存储库。那么,我是否要一次又一次地声明我想要使用它们的每个控制器操作的所有对象?我想这一定存在一种更聪明的方法,但目前我不明白是哪一种。

4

1 回答 1

2

定义StrutturaManager服务并将其注入EntityManager其中。这样管理器就可以访问您需要的存储库,而控制器将不知道 Doctrine 或存储库——这是一个很好的做法。

于 2012-09-18T14:42:15.437 回答