《PHP實例:Yii中Model(模型)的創建及使用方法》要點:
本文介紹了PHP實例:Yii中Model(模型)的創建及使用方法,希望對您有用。如果有疑問,可以聯系我們。
相關主題:YII框架
PHP學習本文實例分析了Yii中Model(模型)的創建及使用辦法.分享給大家供大家參考,具體如下:
PHP學習YII 實現了兩種模型,表單模型(CFormModel類)和Active Record模型(CAtiveRecord類),它們都繼承自CModel類. CFormModel代表的數據模型是從HTML表單收集的輸入,封裝了所有邏輯(如表單的驗證和其它業務邏輯,應用到表單的域上).它能將數據存儲在內 存中,或者在一個Active Record的贊助下,存入數據庫里.
PHP學習數據庫連接操作
PHP學習在config/main.php中
PHP學習
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=oss',
'emulatePrepare' => true,
'username' => 'root',
'password' => 'hahaha',
'charset' => 'utf8',
//表前綴
'tablePrefix'=>"oss_"
),
PHP學習打開注釋,php要支持pdo
PHP學習查看操作日志
PHP學習
//顯示日志信息,包括sql的查詢信息
array(
'class'=>'CWebLogRoute',
),
PHP學習將注釋打開
PHP學習一. 基于CActiveRecord的Model
PHP學習Active Record(AR) 是一種設計模式,用面向對象的方式抽象的拜訪數據,Yii中,每一個AR對象的實例都可以是CActiveRecord類或者它的子類.它包裝了數據庫表 或視圖中的一行記錄,并封裝了所有的邏輯和風聞數據庫的細節,有大部分的業務邏輯,必須使用這種模型.數據庫表中一行每列字段的值對應AR對象的一個屬 性.它將表映射到類,行映射到對象,列則映射到對象的數據.也就是說每一個Active Record類的實例代表了數據庫中表的一行.但一個 Active Record類不單單是數據庫表中的字段跟類中屬性的映射關系.它還需要在這些數據上處理一些業務邏輯,定義了所有對數據庫的讀寫操作.
PHP學習1) 聲明一個基于CActiveRecord 類的Model
PHP學習
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');
}
}
PHP學習2) 使用父類的辦法完成數據庫操作
PHP學習(1) Insert:
PHP學習
$post=new Post;
$post->title='sample post';
$post->content='content for the sample post';
$post->create_time=time();
$post->save();
PHP學習(2) Select: 常用幾種辦法
PHP學習
// 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);
PHP學習(3) Update
PHP學習
// update the rows matching the specified condition
Post::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 conditions
Post::model()->updateCounters($counters,$condition,$params);
PHP學習(4) Delete
PHP學習
$post=Post::model()->findByPk(10); // assuming there is a post whose ID is 10
$post->delete();
// delete the rows matching the specified condition
Post::model()->deleteAll($condition,$params);
// delete the rows matching the specified condition and primary key(s)
Post::model()->deleteByPk($pk,$condition,$params);
PHP學習(5) 使用事務
PHP學習
$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();
}
PHP學習二. 基于CFormModel 的Model
PHP學習編寫表單需要的HTML之前,我們需要決定我們希望用戶輸入哪些數據,以及應該符合什么規則.一個模型類可以用來記錄這些信息,模型是保持用戶輸入并進行驗證的核心
PHP學習根據我們如何使用用戶的輸入,我們可以創建兩種類型的模型.如果用戶輸入的數據被收集,使用,然后丟棄,我們將創建一個表單模型(form model); 如果用戶輸入的數據被保存到數據庫中,我們則會使用 active record .這兩種模型都繼承了他們相同的基類CModel中定義的表單的通用接 口.
PHP學習1) 模型類的定義
PHP學習下面的例子中,我們創建了一個LoginForm模型,用來收集用戶在登陸頁面的輸入.由于登陸信息僅僅用于用戶驗證,并不需要保存,因此我們用form model創建
PHP學習
class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe=false;
}
PHP學習LoginForm一共聲明了三個屬性(attributes),$username、$password、$rememberMe
PHP學習用來記錄用戶輸入的用戶名、暗碼、以及是否記住登陸的選項.因為$rememberMe有了默認值false,所以顯示表單時對應的選框是沒有勾選的.
PHP學習提示:我們使用名"attributes",而不是"properties",來把他們和正常的屬性(properties)進行區分.
PHP學習2) 聲明驗證規則
PHP學習一旦把用戶提交的數據填充到模型,在使用之前,我們要檢查他們是否合法.這是通過對輸入進行一組規則驗證實現的.我們在rulers()辦法中通過配置一個數組來定義驗證規則
PHP學習
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.');
}
}
}
PHP學習上面的代碼指明了用戶名和暗碼是必須得,暗碼需要被驗證,rememberMe必須是布爾型
PHP學習rules()中返回的每條規則,必須依照如下格式
PHP學習array('AttributeList', 'Validator', 'on'=>'ScenarioList', ...附加選項(additional options))
PHP學習AttributeList 是一個被逗號分隔的需要驗證的屬性名列表.Validator 指出了需要做怎樣的驗證.可選的on 參數指出了該規則應用的場景列表,(additional options)是對應的name-value,用于初始對應驗證器的相關屬性
PHP學習在一個規則中指定Validator有三種方法,首先Validator可以使該類的一個方法,比如上面例子中的authenticate.該Validator方法必須依照如下的格式聲明
PHP學習提示:當對active record模型指定規則的時候,我們可以使用特殊的參數‘on',
PHP學習該參數可以使'insert' 或者 'update',可以讓規則分別在插入或者更新的時候適用.如果沒有生命,該規則會在任何調用save()的時候適用.
PHP學習第三、Validator 可以使驗證器類預先定義的別名.在上面的例子中,“required”便是CRequiredValidator的別名,用來驗證屬性不能為空.下面是預定義的驗證器類別名的列表
PHP學習? 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路徑.
PHP學習下面我們給出一些使用預定義驗證器的例子.
PHP學習
// username is required
array('username', 'required'),
// username must be between 3 and 12 characters
array('username', 'length', 'min'=>3, 'max'=>12),
// when in register scenario, password must match password2
array('password', 'compare', 'compareAttribute'=>'password2',
'on'=>'register'),
// when in login scenario, password must be authenticated
array('password', 'authenticate', 'on'=>'login'),
PHP學習3) 平安屬性的設置
PHP學習當一個模型創建之后,我們往往需要根據用戶的輸入,為它填充屬性.這可以方便的通過下面批量賦值的方式來實現
PHP學習
$model=new LoginForm;
if(isset($_POST['LoginForm']))
$model->attributes=$_POST['LoginForm'];
PHP學習最后那條語句便是批量賦值,把$_POST['LoginForm']中每個屬性都賦值到對應的模型屬性中,它等價于下面的語句
PHP學習
foreach($_POST['LoginForm'] as $name=>$value)
{
if($name is a safe attribute)
$model->$name=$value;
}
PHP學習聲明屬性是否是平安屬性是個至關重要的工作.例如,如果我把把數據表的主鍵暴露為平安屬性,那么便可以通過修改主鍵的值,來管理本沒有權限管理的數據,進行攻擊.
PHP學習4) 1.1版中的平安屬性
PHP學習在1.1版中,如果屬性在適用的規則中指定了驗證器,則認為是平安的.例如
PHP學習
array('username, password', 'required', 'on'=>'login, register'),
array('email', 'required', 'on'=>'register'),
PHP學習上面的代碼中用戶名和暗碼屬性在login的場景下不允許為空.用戶名、暗碼郵箱在register的場景下不允許為空.因此如果在login的場景下 進 行批量賦值,僅僅用戶名和暗碼會被賦值,因為login場景下驗證規則里僅出現了這兩個屬性,但是如果是在register場景下,那么這三個屬性都 會被 賦值.
PHP學習
// 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'];
PHP學習那么為什么我們使用如此的策略來決定一個屬性是否是平安屬性呢?因為一個屬性,已經有了一個或者多個對個進行校驗的規則,那么我還需要擔心嗎?
PHP學習需要記住的是,驗證器是用來檢測用戶輸入的數據,而不是我們用代碼產生的數據(例如 時間戳,自增的主鍵等).因此不要給那些不需要用戶輸入的屬性添加驗證器.
PHP學習有時候我們想聲明一些屬性為平安屬性,但是又不必給指定一個驗證規則.例如文章的正文屬性,我們可以允許用戶的任何輸入.為了實現這個目標,我們可以用safe規則.
PHP學習對應的也有一個unsafe規則,來指定哪些屬性是不平安的
PHP學習6) 屬性標簽
PHP學習設計表單的時候,我們需要為用戶的輸入框顯示一個標簽,來提示用戶輸入.盡管我們可以再form中寫死,但是如果我們在相應的模型中指定的話會更加方便和靈活
PHP學習默認情況下,CModel 會簡單的返回屬性的名字作為標簽.這可以通過重寫attributeLabels() 辦法來自定義.在接下來章節中我們將看到,在模型中指定標簽可以讓我們更快更強大的創建一個form表單
PHP學習希望本文所述對大家基于yii框架的php程序設計有所贊助.
《PHP實例:Yii中Model(模型)的創建及使用方法》是否對您有啟發,歡迎查看更多與《PHP實例:Yii中Model(模型)的創建及使用方法》相關教程,學精學透。維易PHP學院為您提供精彩教程。
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/7983.html