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?

Thanks.

+1

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:




<?php

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;

		parent::__construct($scenario);

	}

	

	protected function instantiate($attributes)

	{

		$class=get_class($this);

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

		return $model;

	}


	public function getMetaData()

	{

		if($this->_md!==null)

			return $this->_md;

		else

			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->save();



or:




$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.

http://www.yiiframework.com/forum/index.php/topic/28260-how-to-set-activerecord-table-name-dynamicly/page__p__136002__fromsearch__1#entry136002