Posts Tagged ‘doctrine’

Master & Slave connections in Doctrine 1.2 and Symfony 1.3

December 21st, 2009

http://snippets.symfony-project.org/snippet/373

1. 配置database.yml,设置master,slave数据库连接

2. 覆写Doctrine默认的Query 和Record

public function configureDoctrine(Doctrine_Manager $manager)
{
    // Configure custom query and custom record classes
    $manager->setAttribute(Doctrine::ATTR_QUERY_CLASS, 'MyQuery');
    $options = array('baseClassName' => 'MyRecord');
    sfConfig::set('doctrine_model_builder_options', $options);
}

3. 创建自定义的Query

class MyQuery extends Doctrine_Query
{
  public function preQuery()
  {
      // If this is a select query then set connection to the slave
      if (Doctrine_Query::SELECT == $this->getType()) {
          $this->_conn = Doctrine_Manager::getInstance()->getConnection('slave');
      // All other queries are writes so they need to go to the master
      } else {
          $this->_conn = Doctrine_Manager::getInstance()->getConnection('master');
      }
  }
}

4.创建自定义的Record

abstract class MyRecord extends sfDoctrineRecord
{
    public function save(Doctrine_Connection $conn = null)
    {
      $conn = Doctrine_Manager::getInstance()->getConnection('master');
      parent::save($conn);
    }
}

5. 如果你使用的Doctrine Behaviour(比如Versionable)需要创建表,也需要指明

Entity:
  ActAs:
    Versionable:
      builderOptions:
        baseClassName: MyRecord

如果你有多个slave服务器,就在ProjectConfiguration中配置在启动的时候选择一个,同时修改Query对象获得得connection名字