Zend 简单视图-控制器-模型指南

问题描述 投票:0回答:2

我是 Zend 框架的新手。我让控制器与模型交互,然后将该信息发送到视图。

目前我的代码看起来像这样:

//Controller
$mapper = new Application_Model_Mapper();
$mapper->getUserById($userID);      
$this->view->assign('user_name', $mapper->user_name);
$this->view->assign('about', $mapper->about;
$this->view->assign('location', $mapper->location);

//Model
class Application_Model_Mapper
{
    private $database;
    public $user_name;
    public $about;
    public $location;

public function __construct()
{
    $db = new Application_Model_Dbinit;
        $this->database = $db->connect;
}

public function getUserById($id)
{
    $row = $this->database->fetchRow('SELECT * FROM my_table WHERE user_id = '. $id .'');
    $this->user_name = $row['user_name'];
    $this->about = $row['about'];
    $this->location = $row['location'];
}

}

//View
<td><?php echo $this->escape($this->user_name); ?> </td>
<td><?php echo $this->escape($this->about); ?></td>
<td><?php echo $this->escape($this->location); ?></td>

该代码显然并不完整,但您可以想象我如何尝试使用该模型进行操作。我想知道这是否是一个好的 Zend 编码策略?

我想知道,因为如果我从模型中提取更多数据,控制器就会开始变得相当大(每个项目一行),并且模型有很多公共数据成员。

我忍不住认为有更好的方法,但我试图避免让视图直接访问模型。

php model-view-controller zend-framework frameworks
2个回答
2
投票

查看 ZF 团队负责人制作的有关对象建模的幻灯片。

http://www.slideshare.net/weierophinney/playdoh-modelling-your-objects


1
投票

您应该使用完整的对象,而不是通过属性分解和重建它们。

Zend 有一个数据库抽象层,您可以使用它来快速完成它。看看这些

http://framework.zend.com/manual/en/zend.db.html http://framework.zend.com/manual/en/zend.db.table.html

作为起点,开始将完整的(首选数据传输)对象传递给视图。

//This is just a simple example, I'll leave it up to you how you want to organize your models. You can use several strategies. At work we use the DAO pattern. 
$user = $userModel->getUser($id);
$this->view->user  = $user;

And in your view,

Name : <?=$this->user->name?> <br>
About me : <?=$this->user->about?> <br>
© www.soinside.com 2019 - 2024. All rights reserved.