简短的回答是:是的 PHP 可以.
(Note, its not exactly MVP as described in its original paper, but a variation for web)
MVC 和 MVP 之间的区别在于,视图是完全被动的并且不知道模型层。而在MVC它不是被动的并且了解模型层。在适当的MVP, View
类(如果是的话)也不应该实现一个构造函数。
MVP 的典型示例将由以下部分组成:
- 数据访问层(DataMappers、ORM 等)
- 业务逻辑(如验证和计算)
- 被动视图类(它可以是一个模板,但最好坚持使用一个类)
- 连接模型和视图的演示者
如何使用 PHP 实现模型-视图-呈现器的示例
Note: A model in real-world scenario is not class, but abstraction layer, that contain a lot of classes to deal with application logic. I'd call it "Model" for demonstration purposes.
class Model
{
public function getSomeStuff()
{
return array('foo' => 'bar');
}
}
class View
{
public function render($path, array $vars = array())
{
ob_start();
extract($vars);
require($path);
return ob_get_clean();
}
}
class Presenter
{
private $model;
private $view;
public function __construct(Model $model, View $view)
{
$this->model = $model;
$this->view = $view;
}
public function indexAction()
{
$data = $this->model->getSomeStuff();
// Variables are set now, render the HTML
// And returns as a string
return $this->view->render('path/to/template.phtml', $data);
}
}
文件:模板.phtml
<!DOCTYPE html>
<html>
<head>
<title>...</title>
</head>
<body>
<?php foreach($vars as $key => $value): ?>
<p><?php echo $key; ?> : <?php echo $value; ?></p>
<?php endforeach; ?>
</body>
</html>
用法是:
$model = new Model();
$view = new View();
$presenter = new Presenter($service, $view);
echo $presenter->indexAction();
请注意,这是一个非常简化的示例。在现实场景中,任何基于 MVP 的应用程序SHOULD还实现诸如:路由器、SPL 类自动加载器等功能。