麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 開發 > PHP > 正文

Yii中Model(模型)的創建及使用方法

2024-05-04 23:41:33
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了Yii中Model(模型)的創建及使用方法,結合實例形式較為詳細的分析了Yii中模型的基本創建技巧,使用方法及相關注意事項,需要的朋友可以參考下
 

本文實例分析了Yii中Model(模型)的創建及使用方法。分享給大家供大家參考,具體如下:

YII 實現了兩種模型,表單模型(CFormModel類)和Active Record模型(CAtiveRecord類),它們都繼承自CModel類。 CFormModel代表的數據模型是從HTML表單收集的輸入,封裝了所有邏輯(如表單的驗證和其它業務邏輯,應用到表單的域上)。它能將數據存儲在內 存中,或者在一個Active Record的幫助下,存入數據庫里。

數據庫連接操作

在config/main.php中

'db'=>array(  'connectionString' => 'mysql:host=localhost;dbname=oss',  'emulatePrepare' => true,  'username' => 'root',  'password' => 'hahaha',  'charset' => 'utf8',  //表前綴  'tablePrefix'=>"oss_"),

打開注釋,php要支持pdo

查看操作日志

//顯示日志信息,包括sql的查詢信息array(  'class'=>'CWebLogRoute',),

將注釋打開

一. 基于CActiveRecord的Model

Active Record(AR) 是一種設計模式,用面向對象的方式抽象的訪問數據,Yii中,每一個AR對象的實例都可以是CActiveRecord類或者它的子類。它包裝了數據庫表 或視圖中的一行記錄,并封裝了所有的邏輯和風聞數據庫的細節,有大部分的業務邏輯,必須使用這種模型。數據庫表中一行每列字段的值對應AR對象的一個屬 性。它將表映射到類,行映射到對象,列則映射到對象的數據。也就是說每一個Active Record類的實例代表了數據庫中表的一行。但一個 Active Record類不單單是數據庫表中的字段跟類中屬性的映射關系。它還需要在這些數據上處理一些業務邏輯,定義了所有對數據庫的讀寫操作。

1) 聲明一個基于CActiveRecord 類的Model

class Post extends CActiveRecord{public static function model($className=__CLASS__){return parent::model($className);}public function tableName(){return '{{post}}';}public function primaryKey(){return 'id';// return array('pk1', 'pk2');}}

2) 使用父類的方法完成數據庫操作

(1) Insert:

$post=new Post;$post->title='sample post';$post->content='content for the sample post';$post->create_time=time();$post->save();

(2) Select: 常用幾種方法

// find the first row satisfying the specified condition$post=Post::model()->find($condition,$params);// find the row with the specified primary key$post=Post::model()->findByPk($postID,$condition,$params);// find the row with the specified attribute values$post=Post::model()->findByAttributes($attributes,$condition,$params);// find the first row using the specified SQL statement$post=Post::model()->findBySql($sql,$params);$criteria=new CDbCriteria;$criteria->select='title'; // only select the 'title' column$criteria->condition='postID=:postID';$criteria->params=array(':postID'=>10);$post=Post::model()->find($criteria);$post=Post::model()->find(array('select'=>'title','condition'=>'postID=:postID','params'=>array(':postID'=>10),));// find all rows satisfying the specified condition$posts=Post::model()->findAll($condition,$params);// find all rows with the specified primary keys$posts=Post::model()->findAllByPk($postIDs,$condition,$params);// find all rows with the specified attribute values$posts=Post::model()->findAllByAttributes($attributes,$condition,$params);// find all rows using the specified SQL statement$posts=Post::model()->findAllBySql($sql,$params);// get the number of rows satisfying the specified condition$n=Post::model()->count($condition,$params);// get the number of rows using the specified SQL statement$n=Post::model()->countBySql($sql,$params);// check if there is at least a row satisfying the specified condition$exists=Post::model()->exists($condition,$params);

(3) Update

// update the rows matching the specified conditionPost::model()->updateAll($attributes,$condition,$params);// update the rows matching the specified condition and primary key(s)Post::model()->updateByPk($pk,$attributes,$condition,$params);// update counter columns in the rows satisfying the specified conditionsPost::model()->updateCounters($counters,$condition,$params);

(4) Delete

$post=Post::model()->findByPk(10); // assuming there is a post whose ID is 10$post->delete();// delete the rows matching the specified conditionPost::model()->deleteAll($condition,$params);// delete the rows matching the specified condition and primary key(s)Post::model()->deleteByPk($pk,$condition,$params);

(5) 使用事務

$model=Post::model();$transaction=$model->dbConnection->beginTransaction();try{// find and save are two steps which may be intervened by another request// we therefore use a transaction to ensure consistency and integrity$post=$model->findByPk(10);$post->title='new post title';$post->save();$transaction->commit();}catch(Exception $e){$transaction->rollBack();}

二. 基于CFormModel 的Model

編寫表單需要的HTML之前,我們需要決定我們希望用戶輸入哪些數據,以及應該符合什么規則。一個模型類可以用來記錄這些信息,模型是保持用戶輸入并進行驗證的核心

根據我們如何使用用戶的輸入,我們可以創建兩種類型的模型。如果用戶輸入的數據被收集,使用,然后丟棄,我們將創建一個表單模型(form model); 如果用戶輸入的數據被保存到數據庫中,我們則會使用 active record 。這兩種模型都繼承了他們相同的基類CModel中定義的表單的通用接 口。

1) 模型類的定義

下面的例子中,我們創建了一個LoginForm模型,用來收集用戶在登陸頁面的輸入。由于登陸信息僅僅用于用戶驗證,并不需要保存,因此我們用form model創建

class LoginForm extends CFormModel{public $username;public $password;public $rememberMe=false;}

LoginForm一共聲明了三個屬性(attributes),$username、$password、$rememberMe

用來記錄用戶輸入的用戶名、密碼、以及是否記住登陸的選項。因為$rememberMe有了默認值false,所以顯示表單時對應的選框是沒有勾選的。

提示:我們使用名"attributes",而不是"properties",來把他們和正常的屬性(properties)進行區分。

2) 聲明驗證規則

一旦把用戶提交的數據填充到模型,在使用之前,我們要檢查他們是否合法。這是通過對輸入進行一組規則驗證實現的。我們在rulers()方法中通過配置一個數組來定義驗證規則

class LoginForm extends CFormModel{public $username;public $password;public $rememberMe=false;private $_identity;public function rules(){return array(array('username, password','required'),array('rememberMe', 'boolean'),array('password', 'authenticate'),);}public function authenticate($attribute,$params){if(!$this->hasErrors()) // we only want to authenticate when no input errors{$this->_identity=new UserIdentity($this->username,$this->password);if(!$this->_identity->authenticate())$this->addError('password','Incorrect password.');}}}

上面的代碼指明了用戶名和密碼是必須得,密碼需要被驗證,rememberMe必須是布爾型

rules()中返回的每條規則,必須按照如下格式

array('AttributeList', 'Validator', 'on'=>'ScenarioList', ...附加選項(additional options))

AttributeList 是一個被逗號分隔的需要驗證的屬性名列表。Validator 指出了需要做怎樣的驗證。可選的on 參數指出了該規則應用的場景列表,(additional options)是對應的name-value,用于初始對應驗證器的相關屬性

在一個規則中指定Validator有三種方法,首先Validator可以使該類的一個方法,比如上面例子中的authenticate。該Validator方法必須按照如下的格式聲明

復制代碼代碼如下:
public function ValidatorName($attribute,$params) { ... }

其次 Validator 可以使驗證器的類名,當規則適用時,一個驗證器類的實例會被創建并進行實際的驗證。規則里的附加屬性,用于初始實例的相關屬性。驗證器類必須繼承于CValidator

 

提示:當對active record模型指定規則的時候,我們可以使用特殊的參數‘on',

該參數可以使'insert' 或者 'update',可以讓規則分別在插入或者更新的時候適用。如果沒有生命,該規則會在任何調用save()的時候適用。

第三、Validator 可以使驗證器類預先定義的別名。在上面的例子中,“required”便是CRequiredValidator的別名,用來驗證屬性不能為空。下面是預定義的驗證器類別名的列表

? boolean:CBooleanValidator的別名,驗證屬性的值是否是CBooleanValidator::trueValue 或者 CBooleanValidator::falseValue
? captcha:CCaptchaValidator的別名,驗證屬性的值是否和CAPTCHA中顯示的驗證碼的值相等
? compare:CCompareValidator的別名,驗證屬性的值是否等于另一個屬性或者一個常量
? email:CEmailValidator的別名,驗證屬性的值是否是個合法的email地址
? default:CDefaultValueValidator的別名,為屬性指派一個默認值
? exist:CExistValidator的別名,驗證屬性的值是否能在表的列里面找到
? file: CFileValidator 的別名, 驗證屬性是否包含上傳文件的名字
? filter:CFilterValidator的別名,使用一個過濾器轉換屬性的形式
? in: CRangeValidator 的別名, 驗證屬性值是否在一個預訂的值列表里面
? length: CStringValidator 的別名, 確保了屬性值的長度在指定的范圍內.
? match: CRegularExpressionValidator 的別名, 驗證屬性是否匹配一個正則表達式.
? numerical: CNumberValidator 的別名, 驗證屬性是否是一個有效的數字.
? required: CRequiredValidator 的別名, 驗證屬性的值是否為空.
? type: CTypeValidator 的別名, 驗證屬性是否是指定的數據類型.
? unique: CUniqueValidator 的別名, 驗證屬性在數據表字段中是否是唯一的.
? url: CUrlValidator 的別名, 驗證屬性是否是一個有效的URL路徑.

下面我們給出一些使用預定義驗證器的例子。

// username is requiredarray('username', 'required'),// username must be between 3 and 12 charactersarray('username', 'length', 'min'=>3, 'max'=>12),// when in register scenario, password must match password2array('password', 'compare', 'compareAttribute'=>'password2','on'=>'register'),// when in login scenario, password must be authenticatedarray('password', 'authenticate', 'on'=>'login'),

3) 安全屬性的設置

當一個模型創建之后,我們往往需要根據用戶的輸入,為它填充屬性。這可以方便的通過下面批量賦值的方式來實現

$model=new LoginForm;if(isset($_POST['LoginForm']))$model->attributes=$_POST['LoginForm'];

最后那條語句便是批量賦值,把$_POST['LoginForm']中每個屬性都賦值到對應的模型屬性中,它等價于下面的語句

foreach($_POST['LoginForm'] as $name=>$value){if($name is a safe attribute)$model->$name=$value;}

聲明屬性是否是安全屬性是個至關重要的工作。例如,如果我把把數據表的主鍵暴露為安全屬性,那么便可以通過修改主鍵的值,來管理本沒有權限管理的數據,進行攻擊。

4) 1.1版中的安全屬性

在1.1版中,如果屬性在適用的規則中指定了驗證器,則認為是安全的。例如

array('username, password', 'required', 'on'=>'login, register'),array('email', 'required', 'on'=>'register'),

上面的代碼中用戶名和密碼屬性在login的場景下不允許為空。用戶名、密碼郵箱在register的場景下不允許為空。因此如果在login的場景下 進 行批量賦值,僅僅用戶名和密碼會被賦值,因為login場景下驗證規則里僅出現了這兩個屬性,但是如果是在register場景下,那么這三個屬性都 會被 賦值。

// in login scenario$model=new User('login');if(isset($_POST['User']))$model->attributes=$_POST['User'];// in register scenario$model=new User('register');if(isset($_POST['User']))$model->attributes=$_POST['User'];

那么為什么我們使用如此的策略來決定一個屬性是否是安全屬性呢?因為一個屬性,已經有了一個或者多個對個進行校驗的規則,那么我還需要擔心嗎?

需要記住的是,驗證器是用來檢測用戶輸入的數據,而不是我們用代碼產生的數據(例如 時間戳,自增的主鍵等)。因此不要給那些不需要用戶輸入的屬性添加驗證器。

有時候我們想聲明一些屬性為安全屬性,但是又不必給指定一個驗證規則。例如文章的正文屬性,我們可以允許用戶的任何輸入。為了實現這個目標,我們可以用safe規則。

復制代碼代碼如下:
array('content', 'safe')

 

對應的也有一個unsafe規則,來指定哪些屬性是不安全的

復制代碼代碼如下:
array('permission', 'unsafe')

unsafe并不常用,對你以前定義的安全屬性來說,這是個例外
5) 獲取驗證錯誤
當驗證結束后,任何可能的錯誤都存儲在模型的實例中。我們可以通過調用CModel::getErrors() 和 CModel::getError()重新獲取到。這兩個方法的區別在于,第一個可以返回指定模型屬性的所有錯誤,而第二個方法只返回了第一條錯誤。

 

6) 屬性標簽

設計表單的時候,我們需要為用戶的輸入框顯示一個標簽,來提示用戶輸入。盡管我們可以再form中寫死,但是如果我們在相應的模型中指定的話會更加方便和靈活

默認情況下,CModel 會簡單的返回屬性的名字作為標簽。這可以通過重寫attributeLabels() 方法來自定義。在接下來章節中我們將看到,在模型中指定標簽可以讓我們更快更強大的創建一個form表單

希望本文所述對大家基于yii框架的php程序設計有所幫助。



注:相關教程知識閱讀請移步到PHP教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 久久精品久久久久 | 天堂成人一区二区三区 | 天天黄色片 | 日韩欧美电影一区二区三区 | 成人性生活视频在线播放 | 成av人在线观看 | 国产成人午夜高潮毛片 | 国产成人小视频在线观看 | 精品一区二区三区不卡 | 久久久久99一区二区三区 | 深夜视频在线 | 精品国产一区二区三区成人影院 | 日本在线观看视频网站 | 国产黄色录像片 | 九九热视频在线免费观看 | 爱逼爱操综合网 | 久久精品免费网站 | 久久久久免费精品 | 亚洲午夜视频 | 日本成人在线免费 | 99成人精品视频 | 媚药按摩痉挛w中文字幕 | 国内精品免费一区二区2001 | av成人在线免费观看 | 国产porn在线| aaaaa国产欧美一区二区 | 欧美日本在线视频 | 精品一区二区三区四区在线 | 黄色毛片免费视频 | 成人免费电影在线观看 | 国产乱乱视频 | 久久久久久久久久久久久九 | 精品一区二区亚洲 | 久久精品1区2区 | 日本免费不卡一区二区 | 91av久久| 欧美成人鲁丝片在线观看 | 天堂在线中文资源 | 亚洲日本韩国在线观看 | 国产资源视频在线观看 | 91久久99热青草国产 |