Zend Framework应用层的Master/Slave切换
我正在编写一个应用程序,需要在应用程序层内进行主/从切换。现在,我在创建映射器时实例化一个 Zend_Db_Table 对象,然后将DefaultAdapter 设置为从属设备。
现在,在基本映射器类内部,我有以下方法:
public function useWriteAdapter()
{
if(Zend_Db_Table_Abstract::getDefaultAdapter() != $this->_writeDb)
{
Zend_Db_Table_Abstract::setDefaultAdapter($this->_writeDb);
$this->_tableGateway = new Zend_Db_Table($this->_tableName);
}
}
我需要对此进行健全性检查。我不认为开销太大,我只是怀疑一定有更好的方法。
I am writing an application which requires the Master/Slave switch to happen inside the application layer. As it is right now, I instantiate a Zend_Db_Table object on creation of the mapper, and then setDefaultAdapter to the slave.
Now inside of the base mapper classe, I have the following method:
public function useWriteAdapter()
{
if(Zend_Db_Table_Abstract::getDefaultAdapter() != $this->_writeDb)
{
Zend_Db_Table_Abstract::setDefaultAdapter($this->_writeDb);
$this->_tableGateway = new Zend_Db_Table($this->_tableName);
}
}
I need a sanity check on this. I don't think the overhead is too much, I just suspect there must be a better way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尽管您很可能已经想出了解决方案,但我仍然会发布我的做法:
我正在寻找同一问题的解决方案,并提出将逻辑放入适配器中的想法。
我扩展了 Zend_Db_Adapter_Abstract 并添加了布尔属性 $writes。我还为其添加了公共 getter 和 setter 方法。
我的适配器保存两种不同的数据库配置/连接:一种用于主设备(用于写入),一种用于从设备(用于读取)。 (实际上,它不是一个配置,而是很多配置,所以我有一个按权重随机选择的主配置和从配置的池。)
现在我执行以下操作:在执行查询之前,$writes 必须设置为 true 或 false。在 connect() 方法中,适配器根据 $writes 的值连接或使用正确的连接。
Although you most probably already came up with a solution I will still post the way I did it:
I was looking for a solution for the same problem and came up with the idea to put the logic for that into the Adapter.
I extended the Zend_Db_Adapter_Abstract and added the boolean attribute $writes. I added public getter and setter methods for it as well.
My adapter saves two different database-configurations/-connections: one for the master (for writing) and one for the slave (for reading). (Actually it's not one configuration but many so I have kind of a pool of masters and salves which are selected randomly by weight.)
Now I do the following: Before I execute a query $writes must be set to true or false. In the method connect() the adapter connects or uses the right connection depending on the value of $writes.
Zend_Db_Table_Row_Abstract
类型的对象会记住生成它的 Table 对象。但您可以在调用save()
之前更改关联的表。An object of type
Zend_Db_Table_Row_Abstract
remembers what Table object produced it. But you can change the associated Table before you callsave()
.扩展一个执行启动的基类怎么样?
How about something like a base class that you extend which performs the startup?