本文实例分析了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 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);
(4) Delete
$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);
(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()中返回的每条规则,必须按照如下格式
代码如下:
public function ValidatorName($attribute,$params) { ... }
其次 Validator 可以使验证器的类名,当规则适用时,一个验证器类的实例会被创建并进行实际的验证。规则里的附加属性,用于初始实例的相关属性。验证器类必须继承于CValidator
提示:当对active record模型指定规则的时候,我们可以使用特殊的参数‘on',
该参数可以使'insert' 或者 'update',可以让规则分别在插入或者更新的时候适用。如果没有生命,该规则会在任何调用save()的时候适用。
第三、Validator 可以使验证器类预先定义的别名。在上面的例子中,“required”便是CRequiredValidator的别名,用来验证属性不能为空。下面是预定义的验证器类别名的列表
代码如下:
array('content', 'safe')
对应的也有一个unsafe规则,来指定哪些属性是不安全的
代码如下:
array('permission', 'unsafe')
unsafe并不常用,对你以前定义的安全属性来说,这是个例外
5) 获取验证错误
当验证结束后,任何可能的错误都存储在模型的实例中。我们可以通过调用CModel::getErrors() 和 CModel::getError()重新获取到。这两个方法的区别在于,第一个可以返回指定模型属性的所有错误,而第二个方法只返回了第一条错误。
6) 属性标签
设计表单的时候,我们需要为用户的输入框显示一个标签,来提示用户输入。尽管我们可以再form中写死,但是如果我们在相应的模型中指定的话会更加方便和灵活
默认情况下,CModel 会简单的返回属性的名字作为标签。这可以通过重写attributeLabels() 方法来自定义。在接下来章节中我们将看到,在模型中指定标签可以让我们更快更强大的创建一个form表单
希望本文所述对大家基于yii框架的php程序设计有所帮助。

PHPSession失效的原因包括配置錯誤、Cookie問題和Session過期。 1.配置錯誤:檢查並設置正確的session.save_path。 2.Cookie問題:確保Cookie設置正確。 3.Session過期:調整session.gc_maxlifetime值以延長會話時間。

在PHP中調試會話問題的方法包括:1.檢查會話是否正確啟動;2.驗證會話ID的傳遞;3.檢查會話數據的存儲和讀取;4.查看服務器配置。通過輸出會話ID和數據、查看會話文件內容等方法,可以有效診斷和解決會話相關的問題。

多次調用session_start()會導致警告信息和可能的數據覆蓋。 1)PHP會發出警告,提示session已啟動。 2)可能導致session數據意外覆蓋。 3)使用session_status()檢查session狀態,避免重複調用。

在PHP中配置會話生命週期可以通過設置session.gc_maxlifetime和session.cookie_lifetime來實現。 1)session.gc_maxlifetime控制服務器端會話數據的存活時間,2)session.cookie_lifetime控制客戶端cookie的生命週期,設置為0時cookie在瀏覽器關閉時過期。

使用數據庫存儲會話的主要優勢包括持久性、可擴展性和安全性。 1.持久性:即使服務器重啟,會話數據也能保持不變。 2.可擴展性:適用於分佈式系統,確保會話數據在多服務器間同步。 3.安全性:數據庫提供加密存儲,保護敏感信息。

在PHP中實現自定義會話處理可以通過實現SessionHandlerInterface接口來完成。具體步驟包括:1)創建實現SessionHandlerInterface的類,如CustomSessionHandler;2)重寫接口中的方法(如open,close,read,write,destroy,gc)來定義會話數據的生命週期和存儲方式;3)在PHP腳本中註冊自定義會話處理器並啟動會話。這樣可以將數據存儲在MySQL、Redis等介質中,提升性能、安全性和可擴展性。

SessionID是網絡應用程序中用來跟踪用戶會話狀態的機制。 1.它是一個隨機生成的字符串,用於在用戶與服務器之間的多次交互中保持用戶的身份信息。 2.服務器生成並通過cookie或URL參數發送給客戶端,幫助在用戶的多次請求中識別和關聯這些請求。 3.生成通常使用隨機算法保證唯一性和不可預測性。 4.在實際開發中,可以使用內存數據庫如Redis來存儲session數據,提升性能和安全性。

在無狀態環境如API中管理會話可以通過使用JWT或cookies來實現。 1.JWT適合無狀態和可擴展性,但大數據時體積大。 2.Cookies更傳統且易實現,但需謹慎配置以確保安全性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Dreamweaver CS6
視覺化網頁開發工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)