InitSQLs with authenticated username

I’m looking for a way to execute two database commands at each database connection.

One of the commands must contain the authenticated user’s name.

CDbConnection’s initSQLs looks like the answer, but I’m having trouble finding the right place to add to initSQLs, i.e., some time after Yii::app()->user->name is set.

CWebUser::afterLogin doesn’t work, as it only fires on the initial login.

Maybe set it in your base controller in components/Controller.php in init()?




if (Yii::app()->user->isGuest)

    Yii::app()->setComponents(array('db'=>array('initSQLs'=>...)));

You need to provide an array here, because Yii would instantiate the db component and thus init it before you could change the property.

Thanks for your suggestion. I’m implementing as a site-specific CDbConnection extension:




<?php

class ChgDbConnection extends CDbConnection {

 

        protected function initConnection($pdo) {

                parent::initConnection($pdo);

 

                if (!Yii::app()->user->isGuest) {

                        $user = Yii::app()->user->name;

                        $sql = "begin env.session_config.set_userid('$user'); end;";

 

                        Yii::trace('initConnection: $sql','ChgDbConnection');

                        $pdo->exec($sql);

                }

        }

}