搜尋
首頁後端開發php教程YiiFramework的入門知識點總結

YiiFramework的入門知識點總結

Jun 15, 2018 am 11:57 AM
入門知識點

這篇文章主要介紹了YiiFramework入門知識點,結合圖文形式總結分析了YiiFramework創建的具體步驟及使用的相關注意事項,需要的朋友可以參考下

本文總結了YiiFramework入門知識點。分享給大家供大家參考,具體如下:

建立Yii應用骨架

web為網站根目錄
yiic webapp /web/demo

#透過GII建立model和CURD時需要注意

1、Model Generator 操作

#即使在有表前綴的情況下,Table Name中也要填寫表的全名,即包括表前綴。如下圖:

2、Crud Generator 操作

在該介面中,Model Class中填入model名稱。首字母大寫。也可參考在產生model時,在proctected/models目錄中透過model generator產生的檔名。如下圖:

如果對news、newstype、statustype這三個表格產生CURD控制器,則在Model Generator中,在Model Class中輸入:News、newsType、 StatusType。大小寫與建立的檔案名稱的大小寫相同。如果寫成NEWS或NeWs等都不可以。

建立模組注意事項

透過GII建立模組,Module ID一般用小寫。無論如何,這裡填寫的ID決定main.php設定檔中的設定。如下:

'modules'=>array(
  'admin'=>array(//这行的admin为Module ID。与创建Module时填写的Module ID大写写一致
    'class'=>'application.modules.admin.AdminModule',//这里的admin在windows os中大小写无所谓,但最好与实际目录一致。
  ),
),

路由

system表示yii框架的framework目錄
application表示建立的應用(例如d:\wwwroot\blog)下的protected目錄。
application.modules.Admin.AdminModule
表示應用程式目錄(例如:d:\wwwroot\blog\protected)目錄下的modules目錄下的Admin目錄下的AdminModules.php檔案(實際上指的是該檔案的類別的名字)
system.db.*
表示YII框架下的framework目錄下的db目錄下的所有檔案。

控制器中的accessRules說明

/**
 * Specifies the access control rules.
 * This method is used by the 'accessControl' filter.
 * @return array access control rules
 */
public function accessRules()
{
  return array(
    array('allow', // allow all users to perform 'index' and 'view' actions
      'actions'=>array('index','view'),//表示任意用户可访问index、view方法
      'users'=>array('*'),//表示任意用户
    ),
    array('allow', // allow authenticated user to perform 'create' and 'update' actions
      'actions'=>array('create','update'),//表示只有认证用户才可操作create、update方法
      'users'=>array('@'),//表示认证用户
    ),
    array('allow', // allow admin user to perform 'admin' and 'delete' actions
      'actions'=>array('admin','delete'),//表示只有用户admin才能访问admin、delete方法
      'users'=>array('admin'),//表示指定用户,这里指用户:admin
    ),
    array('deny', // deny all users
      'users'=>array('*'),
    ),
  );
}

看以上程式碼註解。

user: represents the user session information.詳情查閱API:CWebUser
CWebUser代表一個Web應用程式的持久狀態。
CWebUser作為ID為user的一個應用程式元件。因此,在任何地方都能透過Yii::app()->user 存取使用者狀態

public function beforeSave()
{
  if(parent::beforeSave())
  {
    if($this->isNewRecord)
    {
      $this->password=md5($this->password);
      $this->create_user_id=Yii::app()->user->id;//一开始这样写,User::model()->user->id;(错误)
      //$this->user->id;(错误)
      $this->create_time=date('Y-m-d H:i:s');
    }
    else
    {
      $this->update_user_id=Yii::app()->user->id;
      $this->update_time=date('Y-m-d H:i:s');
    }
    return true;
  }
  else
  {
    return false;
  }
}

getter方法或/和setter方法

<?php
/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
  /**
   * Authenticates a user.
   * The example implementation makes sure if the username and password
   * are both &#39;demo&#39;.
   * In practical applications, this should be changed to authenticate
   * against some persistent user identity storage (e.g. database).
   * @return boolean whether authentication succeeds.
   */
  private $_id;
  public function authenticate()
  {
    $username=strtolower($this->username);
    $user=User::model()->find(&#39;LOWER(username)=?&#39;,array($username));
    if($user===null)
    {
      $this->errorCode=self::ERROR_USERNAME_INVALID;
    }
    else
    {
      //if(!User::model()->validatePassword($this->password))
      if(!$user->validatePassword($this->password))
      {
        $this->errorCode=self::ERROR_PASSWORD_INVALID;
      }
      else
      {
        $this->_id=$user->id;
        $this->username=$user->username;
        $this->errorCode=self::ERROR_NONE;
      }
    }
    return $this->errorCode===self::ERROR_NONE;
  }
  public function getId()
  {
    return $this->_id;
  }
}

model/User.php

public function beforeSave()
{
  if(parent::beforeSave())
  {
    if($this->isNewRecord)
    {
      $this->password=md5($this->password);
      $this->create_user_id=Yii::app()->user->id;//====主要为此句。得到登陆帐号的ID
      $this->create_time=date(&#39;Y-m-d H:i:s&#39;);
    }
    else
    {
      $this->update_user_id=Yii::app()->user->id;
      $this->update_time=date(&#39;Y-m-d H:i:s&#39;);
    }
    return true;
  }
  else
  {
    return false;
  }
}

更多相關:

/*
由于CComponent是post最顶级父类,所以添加getUrl方法。。。。如下说明:
CComponent 是所有组件类的基类。
CComponent 实现了定义、使用属性和事件的协议。
属性是通过getter方法或/和setter方法定义。访问属性就像访问普通的对象变量。读取或写入属性将调用应相的getter或setter方法
例如:
$a=$component->text;   // equivalent to $a=$component->getText();
$component->text=&#39;abc&#39;; // equivalent to $component->setText(&#39;abc&#39;);
getter和setter方法的格式如下
// getter, defines a readable property &#39;text&#39;
public function getText() { ... }
// setter, defines a writable property &#39;text&#39; with $value to be set to the property
public function setText($value) { ... }
*/
public function getUrl()
{
  return Yii::app()->createUrl(&#39;post/view&#39;,array(
    &#39;id&#39;=>$this->id,
    &#39;title&#39;=>$this->title,
  ));
}

模型中的rules方法

/*
 * rules方法:指定对模型属性的验证规则
 * 模型实例调用validate或save方法时逐一执行
 * 验证的必须是用户输入的属性。像id,作者id等通过代码或数据库设定的不用出现在rules中。
 */
/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
  // NOTE: you should only define rules for those attributes that
  // will receive user inputs.
  return array(
  array(&#39;news_title, news_content&#39;, &#39;required&#39;),
  array(&#39;news_title&#39;, &#39;length&#39;, &#39;max&#39;=>128),
  array(&#39;news_content&#39;, &#39;length&#39;, &#39;max&#39;=>8000),
  array(&#39;author_name, type_id, status_id,create_time, update_time, create_user_id, update_user_id&#39;, &#39;safe&#39;),
  // The following rule is used by search().
  // Please remove those attributes that should not be searched.
  array(&#39;id, news_title, news_content, author_name, type_id, status_id, create_time, update_time, create_user_id, update_user_id&#39;, &#39;safe&#39;, &#39;on&#39;=>&#39;search&#39;),
  );
}

說明:

1、驗證欄位必須為使用者輸入的屬性。不是由使用者輸入的內容,無需驗證。
2、資料庫中的操作欄位(即使是由系統產生的,例如建立時間,更新時間等欄位-在boyLee提供的yii_computer原始碼中,對系統產生的這些屬性沒有放在safe中。見下面代碼)。 對於不是表單提供的數據,只要在rules方法中沒有驗證的,都要加入到safe中,否則無法寫入資料庫

yii_computer的Ne​​ws.php模型關於rules方法

/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
  // NOTE: you should only define rules for those attributes that
  // will receive user inputs.
  return array(
    array(&#39;news_title, news_content&#39;, &#39;required&#39;),
    array(&#39;news_title&#39;, &#39;length&#39;, &#39;max&#39;=>128, &#39;encoding&#39;=>&#39;utf-8&#39;),
    array(&#39;news_content&#39;, &#39;length&#39;, &#39;max&#39;=>8000, &#39;encoding&#39;=>&#39;utf-8&#39;),
    array(&#39;author_name&#39;, &#39;length&#39;, &#39;max&#39;=>10, &#39;encoding&#39;=>&#39;utf-8&#39;),
    array(&#39;status_id, type_id&#39;, &#39;safe&#39;),
    // The following rule is used by search().
    // Please remove those attributes that should not be searched.
    array(&#39;id, news_title, news_content, author_name, type_id, status_id&#39;, &#39;safe&#39;, &#39;on&#39;=>&#39;search&#39;),
  );
}

#檢視中顯示動態內容三種方法

1、直接在檢視檔中以PHP程式碼實作。例如顯示目前時間,在視圖中:

<?php echo date("Y-m-d H:i:s");?>

2、在控制器中實作顯示內容,透過render的第二個參數傳給視圖

控制器方法包含:

$theTime=date("Y-m-d H:i:s");
$this->render(&#39;helloWorld&#39;,array(&#39;time&#39;=>$theTime));

視圖檔:

<?php echo $time;?>

呼叫的render()方法第二個參數的資料是一個array(數組類型),render()方法會提取數組中的值提供給視圖腳本,陣列中的key(鍵值)將是提供給視圖腳本的變數名稱。在這個例子中,數組的key(鍵值)是time,value(值)是$theTime則提取的變數名稱$time是供視圖腳本使用的。這是將控制器的資料傳遞給視圖的一種方法。

3、視圖與控制器是非常緊密的兄弟,所以視圖檔案中的$this指的就是渲染這個視圖的控制器。修改前面的範例,在控制器中定義一個類別的公共屬性,而不是局部變量,它是值就是目前的日期和時間。然後在視圖中透過$this存取這個類別的屬性。

檢視命名約定

檢視檔案命名,請與ActionID相同。但請記住,這只是個推薦的命名約定。其實視圖檔名不必跟ActionID相同,只要將檔案的名字當作第一個參數傳遞給render()就可以了。

DB相關

$Prerfp = Prerfp::model()->findAll(
  array(
    &#39;limit&#39;=>&#39;5&#39;,
    &#39;order&#39;=>&#39;releasetime desc&#39;
  )
);
$model = Finishrfp::model()->findAll(
  array(
    &#39;select&#39; => &#39;companyname,title,releasetime&#39;,
    &#39;order&#39;=>&#39;releasetime desc&#39;,
    &#39;limit&#39; => 10
  )
);
foreach($model as $val){
  $noticeArr[] = "  在".$val->title."竞标中,".$val->companyname."中标。";
}
$model = Cgnotice::model()->findAll (
  array(
    &#39;select&#39; => &#39;status,content,updatetime&#39;,
    &#39;condition&#39;=> &#39;status = :status &#39;,
    &#39;params&#39; => array(&#39;:status&#39;=>0),
    &#39;order&#39;=>&#39;updatetime desc&#39;,
    &#39;limit&#39; => 10
  )
);
foreach($model as $val){
  $noticeArr[] = $val->content;
}
$user=User::model()->find(&#39;LOWER(username)=?&#39;,array($username));
$noticetype = Dictionary::model()->find(array(
 &#39;condition&#39; => &#39;`type` = "noticetype"&#39;)
);
// 查找postID=10 的那一行
$post=Post::model()->find(&#39;postID=:postID&#39;, array(&#39;:postID&#39;=>10));

也可以使用$condition 指定更複雜的查詢條件。不使用字串,我們可以讓$condition 成為一個CDbCriteria 的實例,它允許我們指定不限於WHERE 的條件。例如:

$criteria=new CDbCriteria;
$criteria->select=&#39;title&#39;; // 只选择&#39;title&#39; 列
$criteria->condition=&#39;postID=:postID&#39;;
$criteria->params=array(&#39;:postID&#39;=>10);
$post=Post::model()->find($criteria); // $params 不需要了

注意,當使用CDbCriteria 作為查詢條件時,$params 參數不再需要了,因為它可以在CDbCriteria 中指定,就像上面那樣。

一种替代CDbCriteria 的方法是给find 方法传递一个数组。数组的键和值各自对应标准(criterion)的属性名和值,上面的例子可以重写为如下:

$post=Post::model()->find(array(
 &#39;select&#39;=>&#39;title&#39;,
 &#39;condition&#39;=>&#39;postID=:postID&#39;,
 &#39;params&#39;=>array(&#39;:postID&#39;=>10),
));

其它

1、链接

<span class="tt"><?php echo CHtml::link(Controller::utf8_substr($val->title,0,26),array(&#39;prerfp/details&#39;,&#39;id&#39;=>$val->rfpid),array(&#39;target&#39;=>&#39;_blank&#39;));?></a> </span>

具体查找API文档:CHtml的link()方法

<span class="tt"><a target="_blank"  title="<?php echo $val->title;?>" href="<?php echo $this->createUrl(&#39;prerfp/details&#39;,array(&#39;id&#39;=>$val->rfpid)) ;?>" ><?php echo Controller::utf8_substr($val->title,0,26); ?></a> </span>

具体请查找API文档:CController的createUrl()方法

以上两个连接效果等同

组件包含

一个示例:

在视图中底部有如下代码:

<?php $this->widget ( &#39;Notice&#39; ); ?>

打开protected/components下的Notice.php文件,内容如下:

<?php
Yii::import(&#39;zii.widgets.CPortlet&#39;);
class Banner extends CPortlet
{
  protected function renderContent()
  {
    $this->render(&#39;banner&#39;);
  }
}

渲染的视图banner,是在protected/components/views目录下。

具体查看API,关键字:CPortlet

获取当前host

Yii::app()->request->getServerName();
//and
$_SERVER[&#39;HTTP_HOST&#39;];
$url = &#39;http://&#39;.Yii::app()->request->getServerName(); $url .= CController::createUrl(&#39;user/activateEmail&#39;, array(&#39;emailActivationKey&#39;=>$activationKey));
echo $url;

关于在发布新闻时添加ckeditor扩展中遇到的情况

$this->widget(&#39;application.extensions.editor.CKkceditor&#39;,array(
  "model"=>$model,        # Data-Model
  "attribute"=>&#39;news_content&#39;,     # Attribute in the Data-Model
  "height"=>&#39;300px&#39;,
  "width"=>&#39;80%&#39;,
"filespath"=>Yii::app()->basePath."/../up/",
"filesurl"=>Yii::app()->baseUrl."/up/",
 );

echo Yii::app()->basePath

如果项目目录在:d:\wwwroot\blog目录下。则上面的值为d:\wwwroot\blog\protected。注意路径最后没有返斜杠

echo Yii::app()->baseUrl;

如果项目目录在:d:\wwwroot\blog目录下。则上面的值为/blog。注意路径最后没有返斜杠

(d:\wwwroot为网站根目录),注意上面两个区别。一个是basePath,一个是baseUrl

其它(不一定正确)

在一个控制器A对应的A视图中,调用B模型中的方法,采用:B::model()->B模型中的方法名();

前期需要掌握的一些API
CHtml

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于Yii Framework框架获取分类下面的所有子类的方法

以上是YiiFramework的入門知識點總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
哪些常見問題會導致PHP會話失敗?哪些常見問題會導致PHP會話失敗?Apr 25, 2025 am 12:16 AM

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

您如何在PHP中調試與會話相關的問題?您如何在PHP中調試與會話相關的問題?Apr 25, 2025 am 12:12 AM

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

如果session_start()被多次調用會發生什麼?如果session_start()被多次調用會發生什麼?Apr 25, 2025 am 12:06 AM

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

您如何在PHP中配置會話壽命?您如何在PHP中配置會話壽命?Apr 25, 2025 am 12:05 AM

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

使用數據庫存儲會話的優點是什麼?使用數據庫存儲會話的優點是什麼?Apr 24, 2025 am 12:16 AM

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

您如何在PHP中實現自定義會話處理?您如何在PHP中實現自定義會話處理?Apr 24, 2025 am 12:16 AM

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

什麼是會話ID?什麼是會話ID?Apr 24, 2025 am 12:13 AM

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

您如何在無狀態環境(例如API)中處理會議?您如何在無狀態環境(例如API)中處理會議?Apr 24, 2025 am 12:12 AM

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

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Mac版

SublimeText3 Mac版

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具