這篇文章給大家分享的是有關YII動態模型的示例分析的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
具體如下:
給YII 框架增加動態模型支持
Yii框架中的數據模型使用靜態機制,如果要使用模型方式操作某張數據表,就必須得事先創建數據表對應的模型類(位于 protected/models 目錄下),這種方式,在有的情況下給我們的工作帶來了一些不便,如僅僅將數據表進行顯示,或者數據表是動態生成的,或者要實現數據表模型中的讀寫分離,(如數據寫入與數據呈現邏輯可能定義到不同的模型中,以提高性能,如前后臺的分離)。
為解決這個問題,經過我反復調試,已經為Yii 擴展出了動態數據表模型支持,使用時簡單提供表名,即可將其當作普通的數據表模型進行操作,當然帶來的問題就是無數據驗證。即使是這樣,也給數據顯示帶來極大的方便。如果在使用的過程中有任何問題,可隨時聯系筆者信箱 zhangxugg@163.com 進行探討或索取源碼。
處理方法如下:
請將我提供的DbTable.php 放置到 protected/models/ 目錄下,然后就可以在任何位置使用之。
產生新記錄:
$memo = new DTable('{{memo}}');
$memo->msg = 'this is content';
$memo->save();
//last insertid
echo $memo->id ;讀取已有記錄:
$memo = DTable::model('{{memo}}')->findByPk(12);
$memo->msg = "modefid content";
$memo->save();
//使用非默認數據庫,需要在 config/main.php 文件中定義數據庫連接,如:
'components' => array(
'db-other'=>array(
'class' => 'CDbConnection',
'connectionString' => 'mysql:host=localhost;dbname=cdcol;charset=utf8',
'username' => 'root',
'password' =>'',
'tablePrefix' => '',
'autoConnect' => false,
),
);
DTable::$db = Yii::app()->getComponent('db-other');
$memo = DTable::model('{{memo}}')->findByPk(12);Dynamic model supports for Yii framework 1.1.10
/**
* DTable class file.
* @author zhangxugg@163.com
* @since Yii 1.1.10
* @package application.models
* @version $Id DTable.php 1 2012-03-24 23:29 $
DTable provides dynamic table model supports for some application entironment such as dynamic-generated database tables, or simple read actions.
please contact zhangxugg@163.com for the source code.
new record :
$model = new DTable('table_name');
//use table prefix:
$model = new DTable('{{table_name}}');
$model->id = $id;
$model->name = 'zhangxugg@163.com';
$model->save();
update:
$model = DTable::model('{{table_name}}')
$model->name = 'zhangxugg@163.com'
$model->save();
$list = $model->findAll();
use non-default database connection :
DTable::$db = Yii::app()->getCompoments('db-extra');
tips : you must define the database connection informations in config/main.php
'components' => array(
'db-extra' => array(
'class' => 'CDbConnection',
'connectionString' => 'mysql:host=localhost;dbname=cdcol;charset=utf8',
'username' => 'root',
'password' =>'',
'tablePrefix' => '',
'autoConnect' => false,
),
)
DTable source code :
class DTable extends CActiveRecord {
private static $tableName ;
public function __construct($table_name = '') {
if($table_name === null) {
parent::__construct(null);
} else {
self::$tableName = $table_name ;
parent::__construct();
}
}
public static function model($table_name='')
{
self::$tableName = $table_name ;
return parent::model(__CLASS__);
}
public function tableName()
{
return self::$tableName;
}
}
*/感謝各位的閱讀!關于“YII動態模型的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。