本文转载自
基础总结
yii 默认是 site 控制器,可以在 web.php 中设置
使用自定义默认的控制器。也可以改写
- $config中的'defaultRoute'='xxxx';
属性。 yii 的默认方法是 index,可以在
- Yii::$app->defaultRoute
中进行初始设置,也可以在控制器中改写 defaltAction='action'。
- vender/yiisoft/yii2/base/Controller.php
yii 可以在 modules 文件夹中添加自定义模块,添加完成后在 web.php 中的 $config 中的'modules'=[id=..class=…] 设置模块的开关。
模块一般用于一些独立的功能,像我站里的 admin 模块整体负责后台逻辑。
yii 的模型有 Model 和 ActiveRecord 两种,Model 类用来处理基本的业务逻辑,没有数据库相关方法,如果要操作同名数据表,请继承 ActiveRecord 类。
我们用一个在 models 文件夹中的 Operation.class 里 Operation 类来继承 yii\db\ActiveRecord 来操作 Operation 表。
如果要操作其他表,也可以重写 public $tableName 属性来设置。或改写其 tableName 方法(注意是静态方法) :
- public static function tableName(){return 'tableName'}
yii 的视图层使用. php 文件,而且其内部的实现也多采用 yii 内置小部件的形式,如
来表示其分页类。 而且,像 input 这样的小部件,用 ActiveForm 类来展现,yii 会对每个自动加入 ajax 验证,其一般的小部件都放在 yii\widget \ 里,我们还可以在此文件夹里构建自定义的小部件类。
- <?= LinkPager::widget(['pagination'=>$pagination]) ?>
yii 会默认开启布局模式,其布局模板为 view 中的 layout 中的 main.php,我们可以在
基础类中 public $layout 属性修改模板文件的配置。 我们还可以设置关闭或指定特定的 layout: 控制器内控制
- veder/yiisoft/yii2/web/controller.php
控制器成员方法内控制
- public $layout=false/'layout'
视图中选择布局
- $this->layout=false/'layout'
- $this->context->layout=false/'layout'
yii 中的 view 也使用面向对象方式 ,所以引入 CSS 和 JS 文件要用特殊的方法。
使用
来引入 js 文件; 使用
- $this->registerJsFile('js.js')
来引入 js 文件;
- $this->registerJsFile('js.js')
- //在模型中计算出总数量
- $count = $this - >find() - >where() - >count();
- //用总条数和设定的每页个数实例化一个yii\data\Pagination类
- $page = new Pagination([totalCount ' => $count,'defaultPageSize ' => 2,]);
- //使用分页类的属性搜索想要的数据,并返回数据
- $res=$this->find()->where()->offset($page->offset)->limit($page->limit)->all();
- return [$res,$page];
- //使用控制器渲染页面
- $data=$model->getData();
- return $this->render('index ',$data);
- //在视图页面中使用数据。
- foreach($res as key)...
- yii\widgets\LinkPager::widget([pagination=$page,prevPageLabel='上一页'])'
。
- use yii\helpers\Url;
- Url: :to(['xxx/xxx']);
- //或
- Yii: :$app - >urlManager - >createUrl('xxx.xxx')
yii 里的 QUERY 查询语句构造器非常简单好用,它可以用在模型和控制器中,虽然可能会造成模型与表不对应,但其构成接近 sql 语句,使用它可以轻易写出复杂的 sql 语句而不必严格遵从 yii 的内置规则。
方法为:
- $res = (new yii\db\Query()) - >select() - >from() - >leftJoin() - >where - >() - >all();
其中 where 语句较为复杂:
where('in','id',
) 或 where('id'=>
- $array
) 具体可以查看中对 where 方法的解析。
- $array
yii 里面自定义函数可以在 vendor/yiisoft/yii2/helpers / 文件夹里,新建一个 XXX.php 文件,然后定义一个自定义类,再定义静态方法 YYY()。
使用时应用基命名空间,use yii\helpers\XXX, 然后用类来引用基静态方法 XXX::YYY()
yii 里面的关联模型,用来在取得当前表内的一条记录时,会取出对应表的记录。如 A 表内每取出一条信息,也取出 B 表中跟 A 表对应有信息,在 ModelA 里定义一个 getBtable 方法
- function getBtable() {
- return $this - >hasOne / hasMany(Btable: :className, ['bid' = >'aid']);
- }
查询时可以使用
会在查找时查找其关联对象;也可以使用
- joinWith('Btable')->find();
等方法结果对象 使用
- $this->find()
来直接引用对象。
- $res->btable
来引用 B 表的对应属性。
- $res[n]->btable->attr
yii2 中使用小部件创建 view 视图的步骤: 设置一个 Model 设置其属性
- public $username: public $password;
设置其 rule 或场景等
- public
- function rules() {
- return [[['username', 'password', 'conpass'], 'required'], ['conpass', 'password', ];
- }
设置其 label
- public
- function attributeLabels() {
- return ['username' = >'管理员', 'password' = >'密码', ];
- }
然后在 controller 中将 model 的实例渲染进去:
- $this - >render('index', ['model' = >(new Model / ActiveRecord)])
- //最后在页面中使用ActiveForm
- use yii\widgets\ActiveForm; < ?php $form = ActiveForm: :begin(['action' = >['log/login'], 'method' = >'post']); ? ><?=$form - >field($model, 'username') ? ><?=$form - >field($model, 'password') ? ><div class = "form-group" > <?=html: :submitButton('Submit', ['class' = >'btn btn-primary']) ? ></div>
- <?php ActiveForm::end(); ?>/
在 controller 中设置验证码的独立方法
- public
- function actions() {
- return ['captcha' = > ['class' = >'yii\captcha\CaptchaAction', 'height' = >50, 'width' = >80, 'minLength' = >4, 'maxLength' = >4], ];
- }
在 model 里设置 rule 和 label,label 同上
- public
- function rules() {
- return [['verifyCode', 'captcha', 'captchaAction' = >'admin/log/captcha'], ];
- }
(captchaAction 要设置为 controller 中的位置,如果自定义 module 要设置 module) 在 view 中使用
- use yii\captcha\Captcha; < ?=$form - >field($model, 'verifyCode') - >widget(Captcha: :className(), ['captchaAction' = >'log/captcha', 'imageOptions' = >['alt' = >'点击换图', 'style' = >'cursor:pointer']]) ? >
块内容在
和
- $this->beginBlock(['id'=>xxx])
之间定义,在 layout 中使用
- $this->endBlock()
来引用。可以在完成向模板中导入视图数据。 也可以定义
- $view->block[id]
在 layout 中用
- $this->var=xxx;
来引用。
- $this->var
更新
- //查找到一条结果
- $res = $this - >find() - >where() - >one();
- //对结果修改
- $res - >attr = 'xxx';
- //执行更新操作
- $res - >update();删除
- //删除一条数据
- $this - >findOne($id) - >delete();
- //删除所有符合条件的数据
- $this - >deleteAll([where]);
注意和窍门
在模块中用 Url::to() 方法创建 URL 时,会自动在前面添加模块名,导致无法跳转到其他模块,我们可以在字符串前添加'//'符来返回根模块,例如 Url::to(['//index/index']) 表示跳转到初始地址。
想在控制器中每一个操作前,初始化一个变量的话不要重写__construct 构造函数,因为它需要传入各种变量。最好重写 beforeAction() 函数,它会在执行每一个 action 时都执行一下。
并且注意:方法的最后一定要添加 return true 语句。
若想在 JS 中使用 YII 的 URL 变量等,可以使用 html 中的 script 标签,将变量在第一次渲染视图时预先解析出来,将下面代码放在需要使用变量的地方之前。
- <script type="text/javascript">
- var key = "<?=Url::to(['xxx/xxx']) ?>"
- </script>
然后在 JS 文件中正常使用。
我们可以在 config 文件夹中的 params.php 中定义全局常量。
然后在脚本中用 Yii::$app->params['key'] 来引用。
YII 用 toArray() 方法可以将模型的属性转换为数组进行输出,可独立使用,也可以在查询时用连续操作方式使用。
一定要在 render 前加 echo 或 return 写作
- echo/return $this->render('view',$data);
在 ActiveForm 中如果数据表中有了此字段,就不要再用 public 声明一个属性了,会导致 attribute 无法赋值。。。。(血泪)。
来源: http://lib.csdn.net/article/php/42839