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提供)查詢我的數據庫,一些闡述,並返回一個列表,我將呈現到模板上。
第一個問題:這是「代碼分離」好還是存在一個更好的方式來做我想做的事情?
第二個問題:假設現在我想用StrutturaManager
類型的對象代入indexAction
。請記住,我的對象需要一個存儲庫。那麼,我是否需要再次聲明所有控制器的行爲以及我想要使用它們的所有對象?我想這必須存在一個更聰明的方法,但目前,我不明白哪一個。
好的,這是我的第一個想法。然而,Theres一個「但是」。假設我遵循了你的建議。我有我的服務等。我是否需要在每個動作中用'$ this-> get('struttura_manager')'回憶它(假設struttura_manager是這個服務的註冊名稱)? – DonCallisto
是的。或者你可以[將控制器定義爲服務](http://symfony.com/doc/current/cookbook/controller/service.html),並通過構造函數注入管理器和其他服務,然後像'$ this->一樣使用它們。 strutturaManager'。 –
對我來說是有道理的,但是我擔心的是另一個 - 最後一點,我保證:P - 就是說我擁有10個實體,並且每個實體都有我需要的服務,如xxxxManager,yyyyManager等等? – DonCallisto