使用 ZF 的 Datamapper DB 模式:管理关系数据库
我正在使用 Zend Framework 创建一个应用程序,我想使用数据映射器设计模式来管理我的数据库。我不明白的是如何在关系数据库中使用该模式。
假设我有一个包含帖子的表,其中包含列 id、标题、文本和作者。我可以使用以下类来管理它:
class Application_Model_DbTable_Posts extends Zend_Db_Table_Abstract
{
$_name = 'posts';
}
class Application_Model_PostMapper
{
public function setDbTable($dbTable);
public function getDbTable();
public function save($post);
public function find($id);
public function fetchAll();
}
class Application_Model_Post
{
protected $_id;
protected $_title;
protected $_text;
protected $_author;
public function __set($name, $value);
public function __get($name);
}
现在,假设我想创建一对多关系——例如注释——我将如何做到这一点?以及多对多关系? ——或者会像一对多那样完成吗?
如果可能,请在您的答案中提供代码示例,以帮助我理解。
I am creating an application using Zend Framework and I want to use the data mapper design pattern for managing my database. What I don't understand is how to use the pattern with a relational database.
Suppose I have a table containing posts with columns id, title, text and author. I could use the following classes to manage this:
class Application_Model_DbTable_Posts extends Zend_Db_Table_Abstract
{
$_name = 'posts';
}
class Application_Model_PostMapper
{
public function setDbTable($dbTable);
public function getDbTable();
public function save($post);
public function find($id);
public function fetchAll();
}
class Application_Model_Post
{
protected $_id;
protected $_title;
protected $_text;
protected $_author;
public function __set($name, $value);
public function __get($name);
}
Now, suppose I wanted to create a one-to-many relationship -- comments, for example -- how would I do this? And a many-to-many relationship? -- or would that be done the same was as a one-to-many?
Please provide code samples in your answers if possible, in order to help me understand.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,如果您的 Application_Model_Post 模型具有 Application_Model_Comments 的集合,您可以为评论设置适当的 Db_Table 和 Mapper,并以某种方式扩展您的 Post 模型,以获取特定帖子的评论。
您可能决定将 CommentMapper 注入您的 Post 模型中:
请注意,您的 Post 模型仍然对持久层一无所知。有关加载评论的所有详细信息都在 CommentMapper 中抽象出来。
Generally speaking, if your Application_Model_Post models has a collection of Application_Model_Comments, you would set up appropriate Db_Table and Mapper for comments, and extend your Post model in some way, to enable getting comments for a particular post.
You might decide to inject the CommentMapper into your Post model:
Note that your Post model still knows nothing of the persistence layer. All the details about loading comments is abstracted away in your CommentMapper.