Difference between #1 and #2 of MigrateCommand class for multiple sites using one code base

unchanged
Title
MigrateCommand class for multiple sites using one code base
unchanged
Category
How-tos
unchanged
Tags
changed
Content
My CMS supports multiple sites using one code base therefore the db connection
can only be configured by detecting the site's domain.

As Yii's MigrateCommand class does not support a domain parameter and
configuring the db connection in the console.php is impossible in this case, I
have extended the MigrateCommand as below.

~~~
[php]
class XMigrateCommand extends MigrateCommand
{
    public $domain = '';
    protected $_db;
    
    public function beforeAction($action,$params)
    {
        if
(in_array(strtolower($action),array('up','down','safeup','safedown','redo','to','new','history','mark'))(in_array(strtolower($action),array('up','down','safeup','safedown','redo','to','new','history','makr'))
&& $this->domain == '')
        {
            echo 'You need to specify the domain as Xpress support multi-sites
and multi-database.',"\n",'i.e:
--domain=www.domain.com',"\n";
            return false;
        }
        
        return parent::beforeAction($action,$params);
    }
    
    protected function getDbConnection()
    {
        if($this->_db!==null)
            return $this->_db;
        else
        {        
            // environment file locates in /sites/env folder using this naming
convention: config.domain.php
            $envFile = 'config.'.$this->domain.'.php';
            $envFile = Yii::app()->basePath.'/../sites/env/'.$envFile;
            if (file_exists($envFile))
            {
                include ($envFile);
                $db = $dbs['default'];
                $this->_db = new
CDbConnection($db['connectionString'],$db['username'],$db['password']);
                return $this->_db;
            }
            else
            {
                echo "Error: {$envFile} is not found. Invalid domain or
this domain is not configured properly.";
                exit(1);
            }
        }

        echo "Error: CMigrationCommand.connectionID
'{$this->connectionID}' is invalid. Please make sure it refers to the ID of a
CDbConnection application component.\n";
        exit(1);
    }
}
~~~

With this class, you can run migrate commands adding the --domain=... parameter.
You will need to modify the code in getDbConnection to suite your need
considering:

  * My env file is located in sites/env folder with this naming convention:
config.<domain>.php, i.e. config.abc.com.php
  * In the env file, there are many db connections defined. Each is a item of
the $dbs[ ]

~~~
[php]
$dbs['default']['connectionString'] = 'mysql:...';
$dbs['default']['username'] = 'username';
$dbs['default']['password'] = 'password';
~~~
Write new article
  • Written by: Hudson Nguyen
  • Category: How-tos
  • Yii Version: 1.1
  • Votes: +1
  • Viewed: 2,743 times
  • Created on: Dec 9, 2012
  • Last updated: Dec 9, 2012