Yii中Model(模型)的建立及使用方法_php執行個體

來源:互聯網
上載者:User
本文執行個體分析了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 的別名, 驗證屬性是否匹配一個Regex.
? 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程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.