Table adapter class like Zend_db_Table

Hi Friends,

I’m new to Yii and I was using Zend framework for long time. Comparing to Zend, yii have good performance and light weight. I was looking to use the DB classes in Yii and searched for the available options to work with. I found we can use CActiveRecord class to do that. But I was searching for an easy way to implement the table operations as i was able to do with the Zend_Db_Table class where I can simply create an Zend_Db_Table object with the table name as a parameter as below.

$empobj = new Zend_Db_Table('tbl_employee');

If we have a similar feature like this in Yii, it would be easy and flexible to use as its more friendly and suits for rapid coding. I’m not sure similar mechanism is exists with the new releases, But I checked in forums and websites and i was unable to find something similar to this. Its just my thought :)

Is it possible to have some features like this in the framework 2.0?



Quite often you simply need to perform basic read/write on a table in an OOP fashion. As long as you don’t need any further validation or other advanced features, there’s no need to create a new class for it. You might end up with loads of ‘scaffolding’ code that does nothing whatsoever.

Here’s one solution to this problem:


class DynamicActiveRecord extends CActiveRecord


	protected $_tableName;

	protected $_md; //must redeclare, as parent::_md is private. Why not protected, Qiang?

	public function __construct($scenario = 'insert', $tableName = null)


		$this->_tableName = $tableName;




	protected function instantiate($attributes)



		$model=new $class(null, $this->tableName());

		return $model;


	public function getMetaData()



			return $this->_md;


			return $this->_md = new CActiveRecordMetaData($this);



	public function tableName()


		if (!$this->_tableName)

			$this->_tableName = parent::tableName();

		return $this->_tableName;	



	public static function forTable($tableName)


		return new DynamicActiveRecord('insert', $tableName);



Then you can do something like:

$user = DynamicActiveRecord::forTable('user');

$user->name = 'Pavle';



$user = DynamicActiveRecord::forTable('user')->findByPk(1);

echo $user->name;

Obviously, this should be properly tested first. Hopefully some Yii developer will comment if this is OK.

Please refer to this post which is with the solution.