从头开始学习yii2---6.yii一些小技能

这章我准备是个完结篇,但是会包含很多yii2一些技能。还是很实用的。结合的是一个慕课网上的讲解的博客系统的代码。我一个一个的来描述其中我以前不知道,现在感觉很有用的东西。
详细的项目地址我已经提交到github上了。有兴趣的各位可以前去查看,克隆代码进行修改。
博客网github地址:https://github.com/ChaozhangXue/yiiBlog

1.面包屑

$this->title = '创建';
$this->params['breadcrumbs'][] = ['label' => '文章', 'url' => ['post/index']];
$this->params['breadcrumbs'][] = $this->title;

2.场景

3.自定义组件

4.active form

Yii::$app->session->setFlash('warning',$model->_lastError);

5.actions方法
其实就是吧actionFunction转化成简单的写法而已

6.behaviors,这个就是规定了控制当中的一些方法

public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['index', 'create', 'upload', 'ueditor'], //要把actions里面的也加进来
                'rules' => [
                    [
                        'actions' => ['index'],
                        'allow' => true,
//                        'roles' => ['?'],//?表示不登录就能访问的
                    ],
                    [
                        'actions' => ['create', 'upload', 'ueditor'],
                        'allow' => true,
                        'roles' => ['@'],//@表示登录后能访问的方法
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    '*' => ['get','post'], //默认都可以post和get
                    'create' => ['get','post'], //指定单个方法
                ],
            ],
        ];
    }

7.使用场景添加用户

8.连表查询

9.处理后的event

public function _eventAfterCreate($data)
    {

        //添加事件 on是添加事件的方法, 然后后面表示将_eventAddTag这个时间绑定到当前的EVENT_AFTER_CREATE事件,然后将data放进去
        //其中this表示类  _eventAddTag表示加进去的方法名 $data表示数据
        $this->on(self::EVENT_AFTER_CREATE, [$this, '_eventAddTag'], $data);
//        $this->on(self::EVENT_AFTER_CREATE, [$this, '_eventAddTag'], $data);

        //触发事件
        $this->trigger(self::EVENT_AFTER_CREATE);
    }

10 . try catch
11 事务

 public function create()
    {
        //事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $model = new PostsModel();
            $model->setAttributes($this->attributes);
            $model->summary = $this->_getSummary();
            $model->user_id = Yii::$app->user->identity->id;
            $model->user_name = Yii::$app->user->identity->username;
            $model->is_valid = PostsModel::IS_VALID;
            $model->created_at = time();
            $model->updated_at = time();

            if (!$model->save()) {
                throw new \Exception("文章保存失败");
            }
            $this->id = $model->id;

            //调用事件
            //第一个this表示这个表单,然后getAttributes获取表单的数据,后面是model的数据,
            //然后合并 后面覆盖前面
            $data = array_merge($this->getAttributes(), $model->getAttributes());
            $this->_eventAfterCreate($data);

            $transaction->commit();
            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->_lastError = $e->getMessage();
            return false;
        }
    }

12 获取分页数据, 使用pagenation

 /*
     * 获取分页数据
     */
    public function getPages($query, $curPage = 1, $pageSize = 10, $search = null){
        if($search) {
            $query = $query->andFilerWhere($search);
        }

        $data['count'] = $query->count();
        if(!$data['count']){
            return ['count' => 0, 'curPage'=> $curPage, 'pageSize' => $pageSize, 'start' => 0, 'end' =>0, 'data' =>[]];
        }

        //超过指定页数,不取当前传进来的$curPage参数, 最多显示最大页数
        $curPage = (ceil($data['count']/$pageSize) < $curPage)? ceil($data['count']/$pageSize):$curPage;

        //当前页
        $data['curPage'] = $curPage;
        //每页显示条数
        $data['pageSize'] = $pageSize;
        //起始页
        $data['start'] = ($curPage - 1) * $pageSize +1;
        //末页
        $data['end'] = (ceil($data['count']/$pageSize) == $curPage)? $data['count']:($curPage-1)*$pageSize + $pageSize;
        $data['data'] = $query->offset(($curPage-1) * $pageSize)
            ->limit($pageSize)
            ->asArray()
            ->all();//($curPage-1) * $pageSize 开始页

        return $data;
    }

<div class="page"><?=LinkPager::widget(['pagination' => $data['page']]);?></div>

14.Url::to 方法

Url::to(['member/index','id'=>$list['user_id']])

15 . fontawosome

16 . AppAsset

这个是静态资源引入的地方

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace backend\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'statics/css/site.css',
        'statics/css/font-awesome-4.4.0/css/font-awesome.css',
        'statics/css/layout.css',
    ];
    public $js = [
        'statics/js/jquery-ui.js',
        'statics/js/toggles.js',
        'statics/js/layout.js',
        'statics/js/site.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值