【发布时间】:2017-04-19 18:12:35
【问题描述】:
我正在从头构建一个 MVC PHP 框架,但我在模型层方面遇到了一些问题。
我现在拥有的是一个相对基本的 MVC 实现,这是我的入口点( index.php ):
//get the URI
$uri = isset($_SERVER['REQUEST_URI'])
? $_SERVER['REQUEST_URI']
: '/';
//Initializes the request abstraction from URI
$request = new request($uri);
//getting the view class from the request
$viewFactory = new viewFactory();
$view = $viewFactory->getView($request);
$view->setDefaultTemplateLocation(__DIR__ . '/templates');
//getting the data mapper from the connection string
$connectionString = "mysql:host=localhost;dbname=test;username=root;";
$dataMapperFactory = new dataMapperFactory($connectionString);
$dataMapper = $dataMapperFactory->getDataMapper();
$modelFactory = new modelFactory($dataMapper);
//getting controller and feeding it the view, the request and the modelFactory.
$controllerFactory = new controllerFactory();
$controller = $controllerFactory->getController($request,$view,$modelFactory);
//Execute the necessary command on the controller
$command = $request->getCommand();
$controller->{$command}($request);
//Produces the response
echo $view->render();
我认为这是不言自明的,但如果你没有得到什么,或者你认为我犯了一些可怕的错误,请随时告诉我。
无论如何,modelFactory 负责返回控制器可能需要的任何模型。我现在需要实现“模型研究”的逻辑,我认为有两种方法:
第一种方式:实现一个包含所有研究逻辑的 modelSearch 类,然后让我的模型继承它(就像在 Yii2 中一样)。我不喜欢这种方法,因为它会让我实例化一些模型并让它返回自身的其他实例。所以我有一个相同的模型实例化一次来研究和一次(或更多)所有数据,并且不使用搜索方法。 所以我的控制器看起来像这样:
class site extends controller{
public function __construct($view, $modelFactory){
parent::__construct($view, $modelFactory);
/* code here */
}
public function index()
{
$searchModel = $this->modelFactory->buildModel("exemple");
$model = $searchModel->get(["id"=>3])->one();
$this->render('index',['model' => $model]);
}
}
第二种方式:实现一个包含所有研究逻辑的modelSearch类,然后在入口点,而不是实例化modelFactory,我可以实例化modelSearch,并将其提供给dataMapper。然后我将 modelSearch 提供给控制器,控制器会通过询问 modelSearch 来获得他想要的任何模型(它将使用 modelFactory 实例化模型并返回它们),如下所示:
class site extends controller{
public function __construct($view, $searchModel){
parent::__construct($view, $searchModel);
}
public function index()
{
$model = $this->searchModel->get("exemple",["id"=>3])->one();
$this->render('index',['model' => $model]);
}
}
这种方式对我来说似乎更正确,但缺点是必须调用 modelSearch 类才能返回任何模型,甚至是空模型。
想法?
TL;DR: modelSearch:我是使用它作为获取模型的独立工具,还是让模型继承自它?
【问题讨论】:
-
是的,没有。那不是你设置 MVC 的锄头。 TBH,根据您的示例,我什至不确定“搜索逻辑”是什么。搜索的抽象应该放在负责的服务实例中,然后在内部处理结果集合的抽象以及使用各种持久性抽象对该集合的检索。
标签: php model-view-controller model