How to connect to multiple databases in Yii2
How to connect to multiple databases in Yii2

To connect to multiple databases in the Yii2 framework, you need to do the following:

1. Create two database configuration files in your site’s config. I keep the connections in separate files, and they look like this (example).

Connection to the first database:

return  [
	'class' => 'yiidbConnection',
	'dsn' => 'mysql:host=127.0.0.1;dbname=work_db1',
	'username' => 'root',
	'password' => '',
	'charset' => 'utf8',
	'tablePrefix' => 'tbl_',
];

Connection to the second database:

return  [
	'class' => 'yiidbConnection',
	'dsn' => 'mysql:host=127.0.0.1;dbname=work_db2',
	'username' => 'root',
	'password' => '',
	'charset' => 'utf8',
	'tablePrefix' => 'tbl_',
];

2. In the main config file, register both connections:

'db' => require(__DIR__ . '/db.php'),
'db2' => require(__DIR__ . '/db2.php'),

read more...

Yii2 using traits in a model and overriding them
Yii2 using traits in a model and overriding them

There’s a saying:

live and learn — and still die a fool

Why am I saying this? It’s about traits in PHP. They’ve been around for quite a while, but I only recently started using them in a new project.

The first thing I had to do was move the attributeLabels method into a trait. Yes, I could have created a single base class and extended it. But I decided to go with traits instead. So, here’s what we have:

namespace commontraitsobject;

use Yii;

trait ObjectModelTrait
{
    /**
     * Labels
     * @return array
     */
    public function attributeLabels()
    {
        return [
			'id' => Yii::t('app', 'ID'),
			'name' => Yii::t('app', 'Name'),
			'desc' => Yii::t('app', 'Description'),
			'index_id' => Yii::t('app', 'Index'),
			'is_active' => Yii::t('app', 'Is active'),
        ];
    }
}

This trait was reused multiple times in models. Here’s one example:

namespace commonmodelsterritory;

use yiidbActiveRecord;

use commontraitsobjectObjectModelTrait;

class TerritoryAreaModel extends ActiveRecord
{
	use ObjectModelTrait;
	
    public static function tableName()
    {
        return '{{%territory_area}}';
    }
}

read more...