I ve created a base model file in the components folder:
class BaseModel extends CModel
{
public static $db;
public function init() {
parent::init();
$this->getDbConnection()->setActive(true);
}
public function attributeNames() {
return array();
}
public function getDbConnection() {
if(self::$db!==null)
return self::$db;
else {
self::$db=Yii::app()->getDb();
if(self::$db instanceof CDbConnection) {
self::$db->setActive(true);
return self::$db;
}
else
throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
}
}
}
?>
My model file is:
class Content extends BaseModel
{
public function getContent() {
$sqlStatement = "SELECT title, body FROM `tbl_content`";
$command=$db->createCommand($sqlStatement);
return($command->queryAll());
}
}
When i try to run getContent() function, i get the following error:
"Fatal error: Call to a member function createCommand() on a non-object"
So what should i do, what is the best way for a DAO warapper to use as a parent class in model files?
You make things pretty complicated . First: CModel doesn’t have a init() method, so your init() is never called. Thus self::$db is empty. It should be sufficient to have it like:
class BaseModel extends CModel
{
public static $db;
public function getDbConnection() {
if(self::$db===null) {
self::$db=Yii::app()->getDb();
self::$db->setActive(true);
}
return self::$db;
}
}
Then in your concrete model $this->getDbConnection() should always give you the same activated connection.