// 新建文件 A.php<?phpnamespacea\b\c;classApple{functioninfo(){echo'this is Apple A';}}// 新建文件 B.php<?phpnamespaced\e\f;classApple{functioninfo(){echo'this is Apple B';}}// 新建文件 C.php<?php// 不存在于任何命名空间:全局类classApple{functioninfo(){echo'this is Apple C';}}// 新建文件 index.php<?phprequire_once('A.php');require_once('B.php');require_once('C.php');// use 关键字:一旦使用 Apple() 类,默认使用 a\b\c 下的 Apple()usea\b\c\Apple;// as 关键字:重命名类名used\e\f\Appleas bApple;// $a_app = new a\b\c\Apple();$a_app=newApple();$a_app2=newApple();$a_app->info();$b_app=newbApple();// 访问全局类$c_app=new\Apple();
<?phpnamespaceapp\models;useyii\db\ActiveRecord;// 创建数据模型,对数据库 Test 进行操作classTestextendsActiveRecord{// 设定表名(如果表名和类名不一致)publicstaticfunctiontableName(){return'test';}publicfunctionrules(){// 验证器参考:https://www.yiichina.com/doc/guide/2.0/tutorial-core-validatorsreturn[['id','integer'],['title','string','length'=>[0,10]]];}}
创建 basic/controllers/TestController.php
<?phpnamespaceapp\controllers;useYii;useyii\web\Controller;useapp\models\Test;// 加载 modelclassTestControllerextendscontroller{publicfunctionactionIndex(){// 1. 单表查询// 查询数据,同时防止 SQL 注入$id='1 or 1=1';$sql="SELECT * FROM test WHERE id = :id";$results= Test::findBySql($sql,[':id'=>$id])->all();// 返回一个数组,数组里面是 id = 1 的对象// id = 1;$results= Test::find()->where(['id'=>1])->all();// id > 0;$results= Test::find()->where(['>','id',0])->all();// id >= 1 AND id <= 2$results= Test::find()->where(['between','id',1,2])->all();// title like "%title1%"$results= Test::find()->where(['like','title','title1'])->all();// 更多 where 方法参考:https://www.yiichina.com/doc/api/2.0/yii-db-queryinterface#where()-detail// 对象在内存里的占用量比数组高,所以要优化// 查询结果转化为数组$results= Test::find()->where(['like','title','title1'])->asArray()->all();// 批量查询foreach(Test::find()->asArray()->batch(1)as$tests){print_R($tests);}// 另: createCommand() 查询// $sql = "SELECT * FROM test WHERE id = " . $id;// $results = Yii::$app->db->createCommand($sql)->queryAll();// 2. 单表删除:调用对象 delete() 方法$results= Test::find()->where(['id'=>1])->all();$results[0]->delete();// 删除条件
Test::deleteAll('id>:id',[':id'=>0]);echo'<pre>';print_R($results);// 3. 单表添加数据$test=newTest;$test->title='title4';// 调用 model 设置的验证器$test->validate();if($test->hasErrors()){echo$test->getErrors();
exit;}// $test->save();// 4. 单表数据修改$test= Test::find()->where(['id'=>3])->one();//print_r($test);$test->title='title33';$test->save();}}