Zend 框架 - 数据库表单例
我发现自己在代码中这样做是为了“缓存”实例化我的 Zend_Db_Table
模型时完成的工作:
if (Zend_Registry::isRegistered('x_table')) {
$x_table = Zend_Registry::get('x_table');
} else {
$x_table = new Default_Model_DbTable_X;
Zend_Registry::set('x_table', $x_table);
}
令我困扰的是这种方法不是很干燥,今天我意识到单例模式可能是一个更好的方法来做到这一点。问题是,我从来没有写过单例类。当我进行一些网络搜索时,我发现了一些关于 Zend_Db_Table
单例的即兴评论,但没有真正的例子。
我已经配置了元数据缓存。
- 如何使我的
Zend_Db_Table
模型成为单例? - 有陷阱或缺点吗?
编辑:我认为单例是答案的原因是我认为我可以简单地在代码中进行以下调用 $x_table = new Default_Model_DbTable_X;
并且单个实例将如果存在则返回。如果可能的话,我更喜欢这种解决方案。
I have found myself doing this in my code to 'cache' the work done when instantiating my Zend_Db_Table
models:
if (Zend_Registry::isRegistered('x_table')) {
$x_table = Zend_Registry::get('x_table');
} else {
$x_table = new Default_Model_DbTable_X;
Zend_Registry::set('x_table', $x_table);
}
It bothered me that this method isn't very DRY and it dawned on me today that a singleton pattern would probably be a better way to do this. Problem is, I've never written a singleton class. When I did some web searches, I found some offhand comments about Zend_Db_Table
singletons, but no real examples.
I already have meta-data caching configured.
- How do I make my
Zend_Db_Table
models singletons? - Are there pitfalls or downsides?
Edit: My reason for thinking a singleton was the answer is that I thought I could simply have the following calls in my code $x_table = new Default_Model_DbTable_X;
and the single instance would be returned if it existed. If this is possible, I would prefer that solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不在某个合理的地方管理 DbTables 呢?如果没有合适的地方,请创建一个 DbTableManager 类。类似于:
在引导程序中初始化管理器并将其粘贴到注册表中。
然后:
因此,您延迟加载 dbTable 对象,并强制执行类似单例的行为。
如果您愿意,可以通过各种方式使上述静态。
Why not just manage the DbTables in some sensible place? If there's no sensible place, create a DbTableManager class. Something like:
Initialize the manager in your bootstrap and stick it in the registry.
Then:
So, you lazy-load the dbTable objects, and enforce a singleton-like behavior.
You could make the above static in various ways, if you wanted to.