The *Native* solution for datamapper of zend framework
zend framework对model没有具体的实现,你可以使Zend_Db也可以使用Zend_Db_Table甚至可以直接使用SQL或者Doctrine1.2
等到PHP5.3普及后Doctrine2.0的估计会成为主流,在这之前呢,一些解决方法是使datamapper来实现,其中DAL层是使用zend-db,
因为如果再同时使用zend-db-table的话会稍微显得冗余复杂,那么什么最简洁和最简便的方法是什么呢?我觉得下面这篇文章会有些提示
http://www.jonathan-petitcolas.com/fr/zend-framework-base-de-donnees-modeles-et-zend_db_adapter/
Table models
01 <?php
02
03 class PostsTable extends Zend_Db_Table_Abstract
04 {
05 protected $_name = 'posts';
06
07 public function insert(array $data)
08 {
09 $data['created'] = date('Y-m-d H:i:s');
10 return parent::insert($data);
11 }
12 }
13
14 ?>
Model 继承Zend_Db_Table_Row_Abstract,对应一个数据库记录,注意$ table变量
1 <?php
2
3 class Post extends Zend_Db_Table_Row_Abstract
4 {
5 protected $table;
6
7
8 public function getTable()
9 {
10 if (is_null($this->table))
11 {
12 require_once APPLICATION_PATH . '/models/tables/PostsTable.php';
13 $this->table = new PostsTable();
14 }
15
16 return $this->table;
17 }
18
19 public function save(array $data)
20 {
21 $table = $this->getTable();
22 $fields = $table->info(Zend_Db_Table_Abstract::COLS);
23
24 foreach ($data as $field => $value)
25 {
26 if (!in_array($field, $fields))
27 {
28 unset($data[$field]);
29 }
30 }
31
32 return $table->insert($data);
33 }
34
35
36 public function getLatestPosts($numberPosts)
37 {
38 $table = $this->getTable();
39 $select = $table->select()40 ->where('status = ?', 'published') ->where('status = ?', 'published')41 ->order('created')42 ->limit($numberPosts, 0);
43 return $table->fetchAll($select);
44 }45
46
47
48 }
49
50 ?>
控制器
01 <?php
02
03 class PostsController extends Zend_Controller_Action
04 {
05 protected $model;
06
07 protected function getModel()
08 {
09 if(is_null($this->model))
10 {
11 require_once APPLICATION_PATH . '/models/Post.php';
12 $this->model = new Post();
13 }
14
15 return $this->model;
16 }
17 }
18
19 ?>
1 public function listAction()
2 {
3 $model = $this->getModel();
4 $this->view->posts = $model->getLatestPosts(5);
5 }
视图
01 <h1>My blog</h1>
02
03 < ?php foreach($this->posts as $post):?>
04
05 <h2>
06 <a href="<?= $this->url( array( 'controller' => 'posts', 'action' => 'view', 'id' => $post->id ), 'default', true) ?>">
07 < ?= $post->title?>
08 </a>
09 </h2>
10
11 < ?= $post->description ?>
12
13 < ?php endforeach;?>
-------
补充:如果不自定义mapper,而直接使用Table Data Gateway模式的话,zend framework的1.10文档详细了很多。
浙公网安备 33010602011771号