1. Yii1.1:
  2. $_GET 可以表示为 Yii::app()->request->getQuery()
  3. $_POST 可以表示为 Yii::app()->request->post();

控制器:

路由:

  控制器 ID 是一种 'path/to/xyz' 的格式,对应相应的控制器类文件protected/controllers/path/to/XyzController.php, 其中的标志 xyz 应被替换为实际的名字 (例如 post 对应protected/controllers/PostController.php). 动作 ID 是除去 action 前缀的动作方法名。例如,如果一个控制器类含有一个名为actionEdit 的方法,则相应的动作 ID 为 edit

动作:  

  路径别名 application.controllers.post.UpdateAction

  指定动作类文件为protected/controllers/post/UpdateAction.php.

组件事件:

  

  1. public function OnClicked($event)
  2. {
  3. $this->raiseEvent('OnClicked',$event);
  4. }
  5.  
  6. $component->OnClicked = $callback;
  7.  
  8. $callback 指向一个有效的PHP回调
  9.  
  10. 事件句柄也可以是一个PHP 5.3以后支持的匿名函数
  11. $component->OnClicked = function($event)
  12. {
  13.   ......
  14. }

  

组件行为:

  1. $component->attachBehaviour($name,$behaviour);
  2.  
  3. $component->test();
  4.  
  5. $behaviour = $component->tree;
  6.  
  7. $behaviour = $component->ase('tree');
  8.  
  9. $component->disableBehavior($name);
  10. // 下面的代码将抛出一个异常
  11. $component->test();
  12. $component->enableBehavior($name);
  13. // 现在就可以使用了
  14. $component->test();

Best MVC Practices

The central idea behind MVC is  code reusability and separation of concerns.

Model represent the underlying data strcture of a Web application.Models are often shared among different sub-applicatons of a Web application.

View are responsible of presenting models in the format that end users desire.

Controller are the glue that binds models,views and other components together into a runnable application.Controllers are responsible for dealing directly with end user requests.

In a well-designed MVC application,controller are often very thin,containing probably only a few dozen lines of code ;while models are very fat,containing most of the code responsible for representing and manipulating the  data. This is because the data  structure and business  logic represented by models is typically very specific to the particular application,and needs to be heavily customized to meet the specific application requirements;while controller logic often follows a similar pattern across applications and therefore may well be simplified by the underlying framework or the base classes.

安全的特性赋值

  1. $model = new LoginForm;
  2. if(isset ($_POST['LoginForm']))
  3.   $model->attributes = $_POST['LoginForm'];
  4.  
  5. 相当于:
  6. foreach($_POST['LoginForm'] as $name => $value)
  7. {
  8.   if($name is authenticate )
  9.   $model -> $name = $value;
  10. }
  11.  
  12. --------------------华丽的分割线------------------------------
  13. array('username, password', 'required', 'on'=>'login, register'),
  14. array('email', 'required', 'on'=>'register'),
  15.  
  16. 如上所示, username password 特性在 login 场景中是必填项。
  17. username, password email 特性在 register 场景中是必填项。
  18. 于是,如果我们在 login 场景中执行块赋值,就只有 username password 会被块赋值。
  19. 因为只有它们出现在 login 的验证规则中。
  20. 另一方面,如果场景是 register ,这三个特性就都可以被块赋值。
  21.  
  22. // 在登录场景中
  23. $model = new User('login');
  24. if(isset($_POST['User']))
  25.   $model -> attributes = $_POST['User'];
  26.  
  27. //在注册场景中
  28. $model = new User('register');
  29. if(isset($_POST['User']))
  30.   $model-> attributes = $_POST['User'];

触发验证

  1. //在注册场景中创建一个User模型 ,等价于:
  2. //$model = new User;
  3. //$model -> scenario = 'regkster';
  4. $model = new User('register');
  5. // 将输入的值填充到模型
  6. $model -> attributes = $_POST['User'];
  7. //执行验证
  8. if($model->validate()) // if input are validate ....
  9.   ...
  10. else
  11.   ...
  12.  
  13. -----------------------------------------------------
  14. public function rules()
  15. {
  16.   return array( array('username, password', 'required'),
  17.       array('password_repeat', 'required', 'on'=>'register'),
  18.       array('password', 'compare', 'on'=>'register'),
  19.    );
  20. }

创建模型:

  

  

  1. class LoginForm extends CFormModel
  2. {
  3.   public $username;
  4.   public $password;
  5.   public $rememberMe;
  6.  
  7.   private $_identity;
  8.   
  9.   public function rules()
  10.   {
  11.     return array(
  12.       array('username,password' ,'required'),
  13.       array('rememberMe','boolean'),
  14.       array('password','authenticate'),
  15.     );
  16.   }
  17.  
  18.   public function authenticate($attribute , $params)
  19.   {  
  20.     $this-> _identity = new UserIdentity($this-> username ,$this -> password);
  21.     if(!$this-> _identity -> authenticate())
  22.       $this-> addError('password','错误的用户名或密码');
  23.   }
  24.  
  25. }
  26.  
  27. //rules() 返回的每个规则必须是以下格式:
  28. array('AttributeList', 'Validator', 'on'=>'ScenarioList', ...附加选项);

创建动作 :

 

  1. //登录表单的例子
  2. public function actionLogin()
  3. {
  4.   $model = new LoginForm;
  5.   if(isset($_POST['LoginForm']))
  6.   {
  7.     //收集用户输入数据
  8.     $model->attributes = $_POST['LoginForm'];
  9.     //验证用户输入,并在判断输入正确后重定向前一页
  10.     if($model - > validate ())
  11.       $this-> redirect (Yii::app()-> user -> returnURL);
  12.   }
  13.   //显示登录表单
  14.   $this-> render('login',array('model'=> $model));
  15. }
  16.  
  17. ---------------------------------------------------------------------
  18. $model->attributes = $_POST['LoginForm'];
  19.  
  20. 等同于:
  21.  
  22. $model-> username = $_POST['LoginForm']['username'];
  23. $model-> password = $_POST['LoginForm']['password'];
  24. $model-> rememberMe = $_POST['LoginForm']['rememberMe'];
  25. $_POST['LoginForm'] 传递过来的是一个数组

创建表单 :

  1. <div class = "form">
  2. <?php echo CHtml::beginForm(); ?>
  3.   <?php echo CHtml::errorSummary($model); ?>
  4.   <div class = "row">
  5.     <?php echo CHtml::activeLabel($model,'username'); ?>
  6.     <?php echo CHtml::activeTextField($model,'username'); ?>
  7.   </div>
  8.  
  9.   <div class = "row ">
  10.    <?php echo CHtml::activeLabel($model,'password'); ?>
  11.    <?php echo CHtml::activeTextField($model,'password')?>
  12.   </div>
  13.   
  14.   <div class = "row">
  15.    <?php echo CHtml::activeLabel($model,'rememberMe'); ?>
  16.    <?php echo CHtml::activeTextField($model,'rememberMe')?>
  17.   </div>
  18.  
  19.   <div class = "row submit">
  20.     <?php echo CHtml::submitButton('Login'); ?>
  21.   </div>
  22.  
  23.   <?php echo CHtml::endForm(); ?>
  24. </div> <!--form End-->
  25.  
  26. 使用 [CActiveForm], 上面的代码可重写为:
  27.  
  28. <div class = "form">
  29.   <?php $form = $this -> beginWidget('CActiveForm'); ?>
  30.  
  31.   <?php echo $form -> errorSummy($model) ;?>
  32.  
  33.   <div class = "row" >
  34.     <?php echo $form -> label($model,'username'); ?>
  35.     <?php echo $form -> textField($model,'username')?>
  36.   </div>
  37.   
  38.   <div class = "row">
  39.     <?php echo $form-> label($model,"password")?>
  40.     <?php echo $form->textField($model,"password")?>
  41.   </div>
  42.  
  43.   <div class = "row">
  44.     <?php echo $form->label($model ,'rememberMe')?>
  45.     <?php echo $form->textField($model,'rememberMe')?>
  46.   </div>
  47.  
  48.   <div class = "row submit">
  49.     <?php echo CHtml::submitButton('Login')?>
  50.   </div>
  51.  
  52. <?php $this-> endWidget();?>
  53. </div>  <!--form -->

收集表格输入:

  1. public function actionBatchUpdate()
  2. {
  3.   //假设每一项(item)是一个'Item' 的实例
  4.   //提取要通过批量模式更新的项
  5.  
  6.   $items = $this->getItemToUpdate();
  7.   if(isset($_POST['Item']))
  8.   {
  9.     $valid = true;
  10.     foreach($items as $i=> item)
  11.     {
  12.       if(isset($_POST[''Item]['$i']))
  13.         $item->attributes = $_POST['Item'][$i];
  14.       $valid = $valid && $item -> validate();
  15.     }
  16.     if($valid)   //如果所有项目有效
  17.     ...      //则在此处做一些操作
  18.   }
  19.   $this->render('batchUpdate',array('items'=> $items));
  20. }
  21.  
  22. --------------------------------------------------------------
  23. // batchUpdate 视图的工作以在一个 HTML 表格中显示输入项
  24.  
  25. <div class = "form">
  26. <?php echo CHtml::beginForm();?>
  27.   <table>
  28.   <tr><th>Name</th><th>Price</th><th>Count</th><th>Description</th></tr>
  29.   <?php foreach($items as $i=>$item): ?>
  30.   <td><?php echo CHtml::activeTextField($item,"[$i]name"); ?></td>
  31.   <td><?php echo CHtml::activeTextField($item,"[$i]price"); ?></td>
  32.   <td><?php echo CHtml::activeTextField($item,"[$i]count"); ?></td>
  33.   <td><?php echo CHtml::activeTextArea($item,"[$i]description"); ?></td>
  34.   </tr>
  35.   
  36.   <?php endforeach ;?>
  37.  
  38.   </table>
  39.  
  40. <?php echo CHtml::submitButton("Save"); ?>
  41. <?php echo CHtml::endForm();?>
  42.  
  43. </div>

 使用表单生成器

  1. //编写登录 action 代码
  2. public function actionLogin()
  3. {
  4.   $model = new LoginForm();
  5.   $form = new CForm('application.views.site.loginForm',$model);
  6.   if($form->submitted('login') && $form->validate())
  7.   {
  8.     $this-> redirect(array('site/index'));
  9.   }
  10.   else
  11.   {
  12.     $this->render('login',array('form'=> $form));
  13.   }
  14.  
  15. }
  16.  
  17. //login 的视图
  18. <h1>Login</h1>
  19. <div class = "form">
  20. <?php  echo $form ?>
  21. </div>
  22.  
  23. -----------------------------------------
  24. 'gender' =>array(
  25.   'type'=> 'dropdownlist',
  26.   'item'=>User::model()->getGenderOptions(),
  27.   'prompt'=> 'Please select:',
  28. ),
  29. ...
  30. class User extends CActiveRecord
  31. {
  32.   public function getGenderOptions
  33.   {
  34.     return array(
  35.         0=> 'Male',
  36.         1=> 'Female',
  37.     );
  38.   }
  39. }
  40.  
  41. //访问表单元素
  42. $username = $form -> element['username'];
  43. $email = $form -> elements['user']-> elements['email'];
  44. //上面的代码可以简化为:
  45. $username = $form['username'];
  46. $email = $form['user']['email'];

创建一个嵌套的表单

  1. public function actionRegister()
  2. {
  3. $form = new CForm('application.views.user.registerForm');
  4. $form['user'] -> model = new User;
  5.   $form['profile'] -> model = new Profile;
  6.   if($form -> submitted('register') && $form -> validate())
  7.   {
  8.     $user = $form['user'] -> model;
  9.     $profile = $form['profile']->model;
  10.     if($form -> save(false))
  11.     {
  12.       $profile->userID = $user->id;
  13.       $profile->save(false);
  14.       $this->redirect(array('site/index'));
  15.     }
  16.   }
  17. $this->render('register',array('form'=>$form));
  18. }
  19.  
  20. //register 视图脚本
  21. <h1>Register</h1>
  22. <div class = "form">
  23. <?php echo $form ; ?>
  24.  
  25. </div>

定制表单显示

  1. class MyForm extends CForm
  2. {
  3.   public function render()
  4.   {
  5.     $output = $this-> renderBegin(); 
  6.     foreach($this-> getElement() as $element)
  7.       $output .= $element-> render();
  8.     $output .= $this-> renderEnd();
  9.     return $output;
  10.   }
  11. }
  12.  
  13. //视图脚本 _form
  14. <div class = "form">
  15.    $this-> renderPartial('_form',array('form'=>$form));
  16. </div>
  17.  
  18. //通用的表单
  19. some complex UI elements here
  20. <?php echo $form['username']?>
  21. some complex UI elements here
  22. <?php echo $form['password']?>
  23. some complex UI elements here

数据访问对象

  建立数据库连接

  

  1. $connection = new CDbConnection($dsn,$username,$password);
  2. //建立连接, 你可以使用 try...catch 捕获可能抛出的异常
  3. $connection-> active = true;
  4.   ...
  5. $connection -> active = false; // 关闭连接
  6.  
  7. --------------华丽的分割线-------------------------------
  8. SQLite: sqlite:/path/to/dbfile
  9. MySQL: mysql:host=localhost;dbname=testdb
  10. PostgreSQL: pgsql:host=localhost;port=5432;dbname=testdb
  11. SQL Server: mssql:host=localhost;dbname=testdb
  12. Oracle: oci:dbname=//localhost:1521/testdb
  13. ----------------------------------------------------------
  14. 配置
  15. array(
  16.   .....
  17.   'components'=> array(
  18.     .....
  19.     'db' => array(
  20.       'class' => 'CDbConnection',
  21.       'connectionString'=>'mysql:host= localhost;dbname=testdb',
  22.       'username'=>'root',
  23.       'password'=>'password',
  24.       'emulatePrepare'=>true,      // needed by some MySQL installations
  25.     )
  26.  
  27.   )
  28.  
  29. )

执行 SQL 语句

  1. $connection= Yii::app()->db; //假设你已经建立了一个'db'连接
  2. //如果没有,就可能需要显示建立一个连接
  3. //$connection = new CDbConnection($dsn,$username,$password);
  4. $command = $connection -> createCommand($sql);
  5. //可以通过下面语句修改
  6. //$command -> text = $newSQL;
  7.  
  8. ------------------------------------------------------------
  9. $rowCount = $command -> execute();    // 执行无查询SQL
  10. $dataReader = $command-> query();     //执行一个SQL查询
  11. $rows = $command-> queryAll();       //查询并返回结果中的所有行
  12. $row = $command -> queryRow();        //查询并返回结果中的第一行
  13. $column = $command -> queryColumn();    //查询并返回结果中的第一列
  14. $value = $command -> queryScalar();      //查询并返回结果中的第一行的第一个字段

  获取查询结果

  1. $data Reader = $command -> query();
  2. //重复调用read()知道它返回false
  3. while(($row = $dataReader -> read())!= false) { ... }
  4. //使用foreach遍历数据中的每一列
  5. foreach($dataReader as $row ) { ... }
  6. //一次性提取所有行到一个数组
  7. $rows = $dataReader -> readAll();

使用事物

  1. $transaction = $connection-> beginTransaction();
  2. try
  3. {
  4.   $connection -> createCommand($sql1)-> execute();
  5.   $connection -> createCommand($sql2)-> execute();
  6.   //....other SQL executions
  7.   $transaction-> commit();
  8. }
  9. catch(Exception $e)
  10. {
  11.   $transaction-> rollBack(); //回滚
  12.   echo $e;
  13. }

  绑定参数 (占位符)

  1. //一条带有两个占位符":username"和 ":email"的SQL
  2. $sql = "INSERT INTO tbl_user(username,email) VALUES(:username,:email)";
  3. $command = $connection -> createCommand($sql);
  4.  
  5. //用实际的用户名替代占位符":usermame"
  6. $command -> bindParam(":username",$username,PDO::PARAM_STR);
  7.  
  8. //用实际的EMAIL替代占位符":email"
  9. $command -> bindParam(":email",$email,PDO::PARAM_STR);
  10. $command -> execute();
  11.  
  12. // 使用新的参数集插入另一行
  13. $command -> bindParam(":username", $username2,PDO::PARAM_STR);
  14. $command -> bindParam(":email",$email2,PDO::PARAM_STR);
  15. $command -> execute();

  

绑定列

  1. $sql = "SELECT username , email FROM tbl_user";
  2. $dataReader = $connection ->createCommand($sql) -> query();
  3. //使用$username 变量绑定第一列(username)
  4. $dataReader -> bindColumn(1,$username);
  5. //使用$email变量绑定第二列(email)
  6. $dataReader -> bindColumn(2,email);
  7. while($dataReader -> read() != false)
  8. {
  9.   //$username 和 $email 含有当前中的username和email
  10.   ...
  11. }

  使用表前缀

  1. $sql = "SELECT * FORM {{user}}";
  2. $users = $connection -> createCommand ($sql) ->queryAll();

  

Query Builder

  1. $usre = Yii::app()->db->createCommand()
  2.       -> select('id,username,profile')
  3.       -> from('tbl_user u')
  4.       -> join ('tbl_profile p', 'u.id = p.user_id')
  5.       -> where('id = :id',array(':id' = $id))
  6.       -> queryRow();
  7.  
  8. // attaction : the following code will not work
  9.  
  10. $command = Yii::app()-> db-> createCommand('Select * From tbl_user');
  11. //the following line will not append where clause to the above SQL
  12. $command -> where ('id = :id' , array(':id' => $id));
  13.  
  14. -------------------------------------------------------
  15.  
  16. select()
  17. function select($columns = '*')
  18.  
  19. select()
  20. select('id,username')
  21. select('tbl_user.id, username as name')
  22. select(array('id' , 'username'))
  23. select(array('id' , 'count(*) as num'))
  24.  
  25. --------------------------------------
  26. selectDistinct()
  27. function selectDistinct($columns)
  28.  
  29. SELEC DISTINCT `id` ,`username`
  30. --------------------------------------
  31. from()
  32. function from($tables)
  33.  
  34. from('tbl_user')
  35. from('tbl_user u,public.tbl_profile p')
  36. from(array('tbl_user' , 'tbl_profile'))
  37. from(array('tbl_user','(select * from tbl_profile) p'))
  38. -------------------------------------------
  39.  
  40. where()
  41.  
  42. function where($conditions,$params = array())
  43.  
  44. array(oeprator,operand1,operand2,...)
  45.  
  46. where operator can be any of the following :
  47. and:
  48. or:
  49. in:
  50. not in:
  51. like:
  52. not like:
  53. or like:
  54. or not like:
  55. examples of using where:
  56.  
  57. where('id = 1 or id = 2')
  58.  
  59. where('id = :id1 or id = :id2',array(':id1' =>1,':id2' => 2))  
  60.  
  61. where(array('or','id=1','id=2'))
  62.  
  63. where(array('and' ,'id=1',array('or', 'type=2','type=3')))
  64.  
  65. where(array('in','id',array(1,2)))
  66.  
  67. where(array('not in ' ,'id',array((1,2)))
  68.  
  69. where(array('like','name','%Qiang%'))
  70.  
  71. where(array('like','name',array(%Qiang% , %Xue%)))
  72.  
  73. where(array('or like' , 'name',array('%Qiang%' , '%Xue%')))
  74.  
  75. where(array('not like ','name','%Qiang%'))
  76.  
  77. where(array('or not like' ,'name' , array('%Qiang%' , '%Xue%')))
  78.  
  79. $keyword = $_GET['q'];
  80.  
  81. //escape % and _ characters
  82.  
  83. $keyword = strtr($keyword , array('%'=> '\%' , '_'=>'\_'));
  84.  
  85. $command-> where(array('like' , 'title' , '%'.$keyword.'%'));
  86.  
  87. ---------------------------------------
  88.  
  89. anyWhere()
  90.  
  91. function andWhere($conditions ,$params = array())
  92.  
  93. -------------------------------------
  94.  
  95. orWhere()
  96.  
  97. function orWhere($conditions,$params = array())
  98.  
  99. -------------------------------------
  100.  
  101. order()
  102.  
  103. function order($columns)
  104.  
  105. order('name ,id desc')
  106.  
  107. order(array('tbl_profile.name', 'id desc'))
  108.  
  109. ----------------------------------------
  110.  
  111. limit() and offset()
  112.  
  113. function limit($limit, $offset = null)
  114.  
  115. function offset($offset)
  116.  
  117. limit(10)
  118.  
  119. limit(10,20)
  120.  
  121. offset(20)
  122.  
  123. --------------------------------------
  124.  
  125. join()
  126.  
  127. function join($table,$conditions ,$params = array())
  128.  
  129. fucntion leftJoin($table,$conditions,$params = array())
  130.  
  131. function rightJoin($table,$conditions,$params = array())
  132.  
  133. function crossJoin($table)
  134.  
  135. function naturalJoin($table)
  136.  
  137. join('tbl_profile','user_id = id')
  138.  
  139. leftjoin('pub.tbl_profile p','p.user_id = id AND type = :type',array(':type'=>1)
  140.  
  141. ---------------------------------------
  142.  
  143. group()
  144.  
  145. function group($columns)
  146.  
  147. group('name , id')
  148.  
  149. group(array('tbl_profile.name' , 'id'))
  150.  
  151. ----------------------------------------
  152.  
  153. having()
  154.  
  155. function having($conditions , $params = array())
  156.  
  157. having('id=1 or id=2 ')
  158.  
  159. having (array('or' , 'id=1' , 'id=2'))
  160.  
  161. ---------------------------
  162.  
  163. union()
  164.  
  165. function union($sql)
  166.  
  167. union('select * from tbl_profile')

Executing Queries  

  1. $user = Yii::app()->db->createCommand()
  2.     ->select('*')
  3.     ->from('tbl_user')
  4.     ->queryAll();

Retrieving SQLs

  1. $sql = Yii::app()->db->createCommand()
  2.     ->selec('*')
  3.     ->from('tbl_user')
  4.     ->text;

Alternative Syntax of Building Queries

  1. $command -> select(array('id' , 'username'));
  2. $command -> select = array('id' , 'username');
  3.  
  4. $row = Yii::app()-> db->createCommand(array(
  5.   'select' => array('id' , 'username'),
  6.   'from' => 'tbl_user',
  7.   'where' => 'id= :id',
  8.   'params' => array(':id'=>1)
  9. ))->queryRow();

  

Building Multiple Queries

  1. $command = Yii::app()-> db-> createCommand();
  2. $user = $command -> select('*')-> from('tbl_users')->queryAll();
  3. $command-> reset(); // clean up the previous query
  4. $posts = $command -> select('*')->from('tbl_posts')->queryAll();

  Buliding Data Manipulation Queries

  1. insert()
  2. function insert($table,$columns)
  3.  
  4. //build and execute the following sql:
  5. //Insert Into `tbl_user`(`name`,`email`)VALUES(:name,:email)
  6.  
  7. $command -> insert('tbl_user' , array(
  8.   'name' => 'Tester',
  9.   'email'=> 'tester@example.com',
  10. ));
  11.  
  12. ---------------------------------------------
  13. update()
  14. function update($table,$columns , $conditions ='',$params = array())
  15.  
  16. //build and execute the following SQL:
  17. //UPDATE `tbl_user` SET `name` = :name WHERE id= :id
  18.  
  19. $commond -> update('tbl_user',array(
  20.   'name' => 'Tester',
  21. ), 'id = :id' , array(':id' => 1));
  22. -----------------------------------------------
  23. delete()
  24. function delete($table,$conditions='',$params = array())
  25.  
  26. //build and execute the following SQL:
  27. //DELETE FROM `tbl_user` WHERE id = :id
  28.  
  29. $commond -> delete('tbl_user' , 'id=:id' , array(':id ' => 1));
  30.  
  31.   Building Schema Manipulation Queries
  32.  
  33. createTable()
  34. function createTable($table,$columns,$options = null)
  35.  
  36. //CREATE TABLE `tbl_user`(
  37. // `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  38. // `username` varchar(255) NOT NULL,
  39. // `location` point
  40. // )ENGINE=InnoDB
  41.  
  42. createTable('tbl_user' , array(
  43.   'id' => 'pk',
  44.   'username' => 'string NOT NULL',
  45.   'location' => 'point',
  46. ),'ENGINE = InnoDB')
  47. ------------------------------------
  48. renameTable()
  49. function renameTable($table,$newName)
  50.  
  51. //RENAME TABLE `tbl_users` TO `tbl_user`
  52. renameTable('tbl_users' ,'tbl_user');
  53. --------------------------------------
  54. dropTable()
  55. function dropTable($table)
  56.  
  57. dropTable('tbl_user')
  58.  
  59. -----------------------------------
  60. truncateTable()
  61. function truncateTable($table)
  62.  
  63. truncateTable('tbl_user')
  64. ---------------------------------
  65. addColumn()
  66.  
  67. function addColumn($table,$column,$type)
  68.  
  69. //ALTER TABLE `tbl_user` ADD `email` varchar(255) NOT NULL
  70. addColumn('tbl_user', 'email','string NOT NULL')
  71. -------------------------------------------
  72. dropColumn()
  73. function dropColumn($table,$column)
  74.  
  75. //ALTER TABLE `tbl_user` DROP COLUMN `location`
  76. dropColumn('tbl_user' ,'location')
  77.  
  78. --------------------------------------------
  79. renameColumn()
  80. function renameColumn($table,$name,$newName)
  81.  
  82. //ALTER TABLE `tbl_user` CHANGE `name` `username` varchar(255) NOT NULL
  83. renameColumn('tbl_user','name','username')
  84. ---------------------------------------------
  85. alterColumn()
  86. function alterColumn($table ,$column,$type)
  87.  
  88. //ALTER TABLE `tbl_user` CHANGE `username` `username` varchar(255)NOT NULL
  89. alterColumn('tbl_user','username','string NOT NULL')
  90. ------------------------------------------------
  91.  
  92. addForeignKey()
  93. function addForeignKey($name ,$table,$columns ,$refTable, $refColumns,$delete = null , $update = null)
  94.  
  95. //ALTER TABLE `tbl_profile` ADD CONSTRANT `fk_profile_user_id`
  96. //FOREIGN KEY ('user_id') REFERENCES `tbl_user`(`id`)
  97. //ON DELETE CASCADE ON UPDATE CASCADE
  98. addForeignKey('fk_profile_user_id' ,'tbl_profile' , 'user_id','tbl_user','id','CASCADE' ,'CASCADE')
  99. ---------------------------------------------------
  100. dropForeignKey()
  101. function dropForeignKey($name,$table)
  102.  
  103. //ALTER TABLE `tbl_profile` DROP FOREIGN KEY `fk_profile_user_id`
  104. dropForeignKey('fk_profile_user_id' , 'tbl_profile')
  105.  
  106. ------------------------------------------
  107. createIndex()
  108. function createIndex($name,$table,$column,$unique = false)
  109.  
  110. //CREATE INDEX `idx_username` ON `tbl_user` (`username`)
  111. createIndex('idx_username','tbl_user','username')
  112.  
  113. ---------------------------------------------
  114. dropIndex()
  115. function dropIndex($name , $table)
  116.  
  117. //DROP INDEX `idx_username` ON `tbl_user`
  118. dropIndex('idx_username' , 'tbl_user')
  119.  
  120.   
  121.  
  122. Active Record
  123.  
  124. [php]
  125. $post = new Post;
  126. $post -> title = 'sample post';
  127. $post -> content = 'post body content';
  128. $post -> save();
  129.  
  130. [sql]
  131. CREATE TABLE tbl_post (
  132.   id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
  133.   title VARCHAR(128) NOT NULL,
  134.   content TEXT NOT NULL,
  135.   creae_time INTEGER NOT NULL
  136. );

  建立数据库连接

  1. return array(
  2.   'components' => array(
  3.     'db' => array(
  4.       'class' => 'system.db.CDbConnection',
  5.       'connectionString'=>'sqlite:path/to/dbfile',
  6.       //开启表结构缓存(schema caching )提高性能
  7.       //'schemaCachingDuration' => 3600,
  8.      ),
  9.   ),
  10.  
  11. );

  

定义AR类

  1. class Post extends CActiveRecord
  2. {
  3.   public static function model($className = __CLASS__)
  4.   {
  5.     return parent::model($className);
  6.   }
  7.  
  8.   public function tableName()
  9.   {
  10.     return 'tbl_post';
  11.   }  
  12. }
  13.  
  14. -------------------------
  15. 表前缀功能
  16. public function tableName()
  17. {
  18.   return '{{post}}';
  19. }
  20.  
  21. --------------------------------
  22. 设置title列属性
  23. $post = new Post;
  24. $post -> title = 'a sample post';
  25.  
  26. -------------------------------------
  27. 定义主键
  28. public function primaryKey()
  29. {
  30.   return 'id';
  31.   //对于复合主键 ,要返回一个类似如下的数组
  32.    //return array('pk1' , 'pk2');
  33. }

创建记录

  1. $post = new Post;
  2. $post -> title = 'sample post';
  3. $post -> content = 'content for the sample post';
  4. $post -> create_time = time();
  5. $post -> save();
  6.  
  7. ---------------------------------class Post extends CActiveRecord {  public $title = 'please enter a title';  ....}
  8.  
  9. $post = new Post;echo $post-> title; //这显示: please enter a title
  10.  
  11. $post ->create_time = new CDbExpression('NOW()');//$post->create_time = 'NOW()'; 不起作用$post->save();

读取记录

  1. $post= Post::model()-> find($condition,$params);$post = Post::model()->findByPk($postID,$condition,$params);$post = Post::model()->findByAttributes($attributes,$condition,$params);$post = Post::model()->findBySql($sql,$params);
  2.  
  3. //查找postID = 10 的那一行$post = Post::model()-> find('postID = :postID',array(':postID' => 10));
  4.  
  5. $criteria = new CDbCriteria;$criteria -> select = 'title';$criteria -> condition = 'postID = :postID';$criteria -> params = array(':postID'=>10);$post = Post::model() -> find($criteria) ; //$params不需要了//可重写为$post = Post::model()->find(array(  'select' => 'title',  'condition'=> 'postID = :postID',  'params' => array(':postID' => 10),));
  6.  
  7. $posts = Post::model()->findAll($conditions ,$params);$posts = Post::model()->findAllByPk($postIDs,$condition,$params);$posts = Post::model()->findAllByAttributes($attributes,$condition,$params);$posts = Post::model()->findAllBySql($sql,$params);
  8.  
  9. $n = Post::model()-> count($condition,$params);$n = Post::model()->countBySql ($sql ,$params);$exists = Post::model()->exists($condition,$params);

更新记录

  1. $post = Post::model() -> findByPk(10);$post-> title = 'new post title';$post -> save();
  2.  
  3. Post::model()->updateAl($attribute,$condition,$params);Post::model()->updateByPk($pk,$attribute,$condition,$params);Post::model()->updateCounters($counters,$condition,$params);

  删除记录

  1. $post = Post::model()-> findByPk(10);//假设有一个帖子,其ID为10$post->delete(); //从数据表中删除此行
  2.  
  3. //删除符合指定条件的行Post::model()->deleteAll($condition,$params);//删除符合指定条件和主键的行Post::model()->deleteByPk($pk,$condition,$params);

数据验证

  1. if($post -> save()){  //数据有效且成功插入/更新}else{  //数据无效,调用 getError()提取错误信息}
  2.  
  3. $post-> title = $_POST['title'];$post-> content = $_POST['content'];$post-> save();
  4.  
  5. //假设$_POST['Post'] 是一个以列名索引值为值的数组$post -> attributes = $_POST['Post'];$post -> save();

使用AR处理事物

  1. $model = Post::model();$transaction = $model -> dbConnection-> beginTransaction();try{  //查找和保存是可能由另一个请求干预的两个步骤  //这样我们使用一个事务以确保其一致性和完整性  $post = $model-> findByPk(10);  $post -> title = 'new post title';  $post -> save();  $transaction -> commit();}catch(Exception $e){  $transaction -> rollBack();}

命名范围

  1. class Post extends CActiveRecord {    ...  public function scopes()  {    return array(      'published' => array(        'condition' =>'status = 1'      ),      'recently' => array(        'order'=> 'create_time DESC',        'limit' => 5,      ),    );  }}
  2.  
  3. $posts = Post::model()->published()->recently()->findAll();
  4.  
  5. Post::model()->published()->recently()->delete();

参数化的命名范围

  1. public function recently($limit = 5){  $this->getDbCriteria()->mergeWith(array(    'order' => 'create_time DESC',    'limit' => $limit,  ));  return $this;}
  2.  
  3. $posts = Post::model()->published()->recently()->findAll();

默认的命名范围

  1. class Contenr extends CActiveRecord{  public function defaultScope()  {    return array(      'condition' => "language='".Yii::app()->language."'",     );  }}
  2.  
  3. //如果下面的方法被调用,将会自动使用上面定义的查询规则:$contents = Content::model()->findAll();

关系型Active Record

  声明关系

  1. class Post extends CActiveRecord{  ...  public function relations ()  {    return array(      'author' => array(self::BELONGS_TO,'User','author_id'),      'categories' => array(self::MANY_MANY , 'Category' , 'tbl_post_category(post_id,category_id)'),    );  }}
  2.  
  3. class User extends CActiveRecord{  ...  public function relations()  {    return array(      'posts' => array(self::HAS_MANY ,'Post','author_id'),      'profile' => array(self::HAS_ONE,'Profile','owner_id'),    );  }}
  4.  

执行关联查询

  1. //获取ID为10的帖子$post = Post::model()->findByPk(10);//获取帖子的作者(author): 此处将执行一个关联查询$author = $post->author;
  2.  
  3. $posts = Post::model()->with('author') -> findAll();$posts = Post::model()->with('author','categories') -> findAll();
  4.  
  5. $post = Post::model()->with(  'author.profile',  'author.posts',  'categories')->findAll();
  6.  
  7. $criteria = new CDbCriteria;$criteria -> with = array(  'author.profile',  'author.posts',  'categories',);$posts = Post::model()->findAll($criteria);或者 $posts = Post::model()->findAll(array(  'with' => array(    'author.profile',    'author.posts',    'categories',  )));

关系型查询选项

  1. class User extends CActiveRecord{  public function relations()  {    return array(      'posts'=>array(self::HAS_MANY,'Post','author_id',                        'order'=>'posts.create_time DESC',                        'with' => 'categories'),      'profile' => array(self::HAS_ONE ,'profile' ,'owner_id'),    );  } }

Disambiguating Column Names

  1. $posts = Post::model()->with('comments')->findAll();
  2.  
  3. $posts = Post::model()->with('comments')->findAll(array(  'order'=> 't.create_time , comments.create_time'));

  Dynamic Relational Query Options

  

  1. User::model()->with(array(  'posts' =>array('order' => 'post.create_time ASC'),  'profile',))->findAll();
  2.  
  3. $user = User::model()->findByPk(1);$posts = $user -> posts(array('conditon' => 'status =1'));

Relational Query Performance

  1. public function relations(){  return array(    'comments' => array(self::HAS_MANY , 'Comment' ,'post_id','together'=>false),  );}
  2.  
  3. $posts = Post::model()->with(array('comments' => array('together' => false)))->findAll();
  4.  
  5. $posts = Post::model()->with(    'author.profile',    'author.posts',    'categories')->together()->findAll();
  6.  

Statistical Query

  1. class Post extends CActiveRecord {  public function relations()  {    return array(        'commentCount' =>array(self::STAT,'Comment','post_id'),        'categoryCount' => array(self::STAT , 'Category', 'post_category(post_id,category_id)'),    );  }}
  2.  
  3. $posts = Post::model()->with('commentCount' , 'categoryCount') -> findAll();

Relational Query With Named Scopes

  1. $posts = Post::model()->published()->recently()->with('comments')->findAll();
  2.  
  3. $posts = Post::model()->with('comments: recently:approved') ->findAll();
  4.  
  5. class User extends CActiveRecord{  public function relations()  {    return array(      'posts' => array(self::HAS_MANY , 'Post' , 'author_id',            'with'=> 'comments:approved'),    );  }}

数据缓存

  1. Yii::app()->cache()->set($id,$value,30);//保留30秒
  2.  
  3. -------------------------------------------------$value = Yii::app()->cache->get($id);if($value === false){  //缓存中没有找到$value,重新生成  //并将它存入缓存以备以后使用  //Yii::app()->cache()->set($id,$value);}
  4.  
  5. // 此值将在30秒后失效 // 也可能因依赖的文件发生了变化而更快失效Yii::app()->cache()->set($id,$value,30,new CFileCacheDependency('FileName'));

片段缓存

  1. ...别的 HTML内容..<?php if($this->beginCache($id)){?>..被缓存的内容..<?php $this -> endCache(); }?>..别的HTML内容..
  2.  
  3. --------------------------------------------...其他HTML内容... <?php if($this->beginCache($id, array('duration'=>3600))) { ?> ...被缓存的内容... <?php $this->endCache(); } ?> ...其他HTML内容...//如果不设置期限 ,默认是60秒

嵌套缓存

  1. ...其他HTML内容..<?php if($this->beginCache($id1)) {?>...外部被缓存内容...  <?php if($this->beginCacahe($id2)) {?>  ...内部被缓存的内容   <?php $this -> endCache();?>
  1. ...外部被缓存内容...<?php $this->endCache();}?>..其他HTML内容...

页面缓存

  1. public function fileters(){  return array(    array(      'COutputCache',      'duration'=>100,      'varyByParam'=> array('id'),    ),  );}

动态内容

  1. ...别的HTML内容...<?php if($this->beginCache($id)){ ?>..被缓存的片段内容...  <?php $this->renderDynamic($callback); ?>    //$callback是回调函数 ..被缓存的内容..<?php $this->endCache(); ?>..别的HTMl内容...

yii 笔记的更多相关文章

  1. Yii笔记:打印sql、Form表单、时间插件、Mysql的 FIND_IN_SET函数使用、是否是post/ajax请求

    语句部分: yii1版本打印最后一条执行的SQL: $this->getDbConnection()->createCommand()->select()->from()-&g ...

  2. Yii笔记---redirect重定向

    Yii的redirect方法在CControler与CHttpRequest之中都有被定义,CController中的redirect调用了CHttpRequest中的redirect方法.我们平常调 ...

  3. Yii框架学习笔记(二)将html前端模板整合到框架中

    选择Yii 2.0版本框架的7个理由 http://blog.chedushi.com/archives/8988 刚接触Yii谈一下对Yii框架的看法和感受 http://bbs.csdn.net/ ...

  4. yii的学习笔记 基本结构 自用

    Yii 学习笔记 W:YII是什么? Q:Yii 是一个基于组件的高性能 PHP 框架,用于快速开发大型 Web 应用.它使Web开发中的 可复用度最大化,可以显著提高你的Web应用开发速度.Yii ...

  5. YII报错笔记:<pre>PHP Notice &#039;yii\base\ErrorException&#039; with message &#039;Uninitialized string offset: 0&#039; in /my/test/project/iot/vendor/yiisoft/yii2/base/Model.php:778

    YII常见报错笔记 报错返回的代码如下: <pre>PHP Notice 'yii\base\ErrorException' with message 'Uninitialized str ...

  6. PHP工作笔记:使用yii migrate管理、生成数据库

    第一步:进入yii migrate 通过dos(我是win7系统,其他系统类似,就是进入字符界面)打开网站目录 phpStudy/WWW/local/ddc_dlss 输入 ./yii migrate ...

  7. Yii源码阅读笔记(三十五)

    Container,用于动态地创建.注入依赖单元,映射依赖关系等功能,减少了许多代码量,降低代码耦合程度,提高项目的可维护性. namespace yii\di; use ReflectionClas ...

  8. Yii源码阅读笔记(三十四)

    Instance类, 表示依赖注入容器或服务定位器中对某一个对象的引用 namespace yii\di; use Yii; use yii\base\InvalidConfigException; ...

  9. Yii源码阅读笔记(三十三)

    ServiceLocator,服务定位类,用于yii2中的依赖注入,通过以ID为索引的方式缓存服务或则组件的实例来定位服务或者组件: namespace yii\di; use Yii; use Cl ...

随机推荐

  1. MediaPlayer 音频播放 示例

    状态机.流程图.生命周期 对播放音频/视频文件和流的控制是通过一个状态机来管理的.下图显示一个MediaPlayer对象被支持的播放控制操作驱动的生命周期和状态. 椭圆代表MediaPlayer对象可 ...

  2. css09浮动属性

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...

  3. hdu 1728

    //hdu 1728 //这个是一道很经典的迷宫题了,思路感觉...取起点和终点,判断连线是否超过n个弯, //先是从起点出发,上下左右四个方向搜索,找到一条路,把那条路的第一个点压入队列 //然后沿 ...

  4. CSS3 用户界面

    CSS3用户界面 在CSS3中,新的用户界面特性包括重设元素尺寸,盒尺寸以及轮廓等. 用户界面属性: resize box-sizing outline-offset 浏览器支持 属性 浏览器支持 r ...

  5. Android开发手记(11) 滑动条SeekBar

    安卓滑动条的操作特别简单,通过getProgress()可以获得SeekBar的位置,通过setProgress(int progress)可以设置SeekBar的位置.要想动态获取用户对SeekBa ...

  6. [译]一个灵活的 Trello 敏捷工作流

    [译]一个灵活的 Trello 敏捷工作流 翻译自 An Agile Trello Workflow That Keeps Tasks Flexible Getting things done 可不只 ...

  7. Javascript 常用函数【1】

    1:基础知识 1 创建脚本块 1: <script language=”JavaScript”> 2: JavaScript code goes here 3: </script&g ...

  8. GET方式,获取服务器文件

    package com.http.get; import java.io.FileOutputStream; import java.io.IOException; import java.io.In ...

  9. 记录Linux下安装elasticSearch时遇到的一些错误

    记录Linux下安装elasticSearch时遇到的一些错误 http://blog.sina.com.cn/s/blog_c90ce4e001032f7w.html (2016-11-02 22: ...

  10. 基于jQuery编写的页面跳转简单的小插件

    其实这个很简单,就是一个脚本函数和两个参数(url,jupetime), 开始实现步骤: 1.像页面引用一个jquery工具包 2.在javascript脚本编写自定义方法: 方法声明: $.exte ...