本文实例总结了yii框架常用技巧。分享给大家供大家参考,具体如下:

获取当前controller name和action name(在控制器里面使用)

echo $this->id;
echo $this->action->id;

控制器获取当前模块

$this->module->id

不生成label标签

// activeform类
$form->field($model, '字段名')->passwordinput(['maxlength' => true])->label(false)

yii2 获取接口传过来的 json 数据:

yii::$app->request->rawbody;

防止 sql 和 script 注入:

use yii\helpers\html;
use yii\helpers\htmlpurifier;
echo html::encode($view_hello_str) //可以原样显示<script></script>代码
echo htmlpurifier::process($view_hello_str) //可以过滤掉<script></script>代码

大于、小于条件查询

// select * from `order` where `subtotal` > 200 order by `id`
$orders = $customer->getorders()
->where(['>', 'subtotal', 200])
->orderby('id')
->all();

搜索的时候添加条件筛选

$dataprovider = $searchmodel->search(yii::$app->request->queryparams);
// $dataprovider->query->andwhere(['pid' => 0]);
$dataprovider->query->andwhere(['>', 'pid', 0]);
//可选传参
$dataprovider->query->andfilterwhere(['id'=>isset($id)?$id:null]);

有两种方式获取查询出来的 name 为数组的集合 [name1, name2, name3]:

方式一:

return \yii\helpers\arrayhelper::getcolumn(user::find()->all(), 'name');

方式二:

return user::find()->select('name')->asarray()->column();

打印数据:

// 引用命名空间
use yii\helpers\vardumper;
// 使用
vardumper::dump($var);
// 使用2 第二个参数是数组的深度 第三个参数是是否显示代码高亮(默认不显示)
vardumper::dump($var, 10 ,true);die;

表单验证,只要需要一个参数:

public function rules()
{
  return [
    [['card_id', 'card_code'], function ($attribute, $param) {//至少要一个
      if (empty($this->card_code) && empty($this->card_id)) {
        $this->adderror($attribute, 'card_id/card_code至少要填一个');
      }
    }, 'skiponempty' => false],
  ];
}

sql is not null条件查询

// ['not' => ['attribute' => null]]
//['isnull(`attribute`)'=>true]
$query = new query;
$query->select('id, city,state,studentname')
  ->from('student')
  ->where(['isactive' => 1])
  ->andwhere(['not', ['city' => null]])
  ->andwhere(['not', ['state' => null]])
  ->orderby(['rand()' => sort_desc])
  ->limit(10);

校验 point_template_id 在 pointtemplate 是否存在

public function rules()
{
  return [
    [['point_template_id'], 'exist',
      'targetclass' => pointtemplate::classname(),
      'targetattribute' => 'id',
      'message' => '此{attribute}不存在。'
    ],
  ];
}

yii给必填项加星

div . required label:after {
  content:
  " *";
  color:
  red;
}

执行sql查询并缓存结果

$styleid = yii::$app->request->get('style');
$collection = yii::$app->db->cache(function ($db) use ($styleid) {
  return collection::findone(['style_id' => $styleid]);
}, self::seconds_in_minitue * 10);

场景:

数据库有user表有个avatar_path字段用来保存用户头像路径

需求: 头像url需要通过域名http://b.com/作为基本url

目标: 提高代码复用

此处http://b.com/可以做成一个配置

示例:

user.php

class user extends \yii\db\activerecord
{
...
  public function extrafields()
  {
    $fields = parent::extrafields();
    $fields['avatar_url'] = function () {
      return empty($this->avatar_path) ? '可以设置一个默认的头像地址' : 'http://b.com/' . $this->avatar_path;
    };
    return $fields;
  }
...
}

examplecontroller.php

class examplecontroller extends \yii\web\controller
{
  public function actionindex()
  {
    $usermodel = user::find()->one();
    $userdata = $usermodel->toarray([], ['avatar_url']);
    echo $userdata['avatar_url']; // 输出内容: http://b.com/头像路径
  }
}

model 里面 rules 联合唯一规则

复制代码 代码如下: [[‘store_id’, ‘member_name’], ‘unique’, ‘targetattribute’ => [‘store_id’, ‘member_name’], ‘message’ => ‘the combination of store id and member name has already been taken.’],

model多个字段一条规则不同提示

[['name', 'email', 'subject', 'body'], 'required','message'=>'{attribute} 必须'],

标量查询

post::find()->select('title')->where(['user_id' => $userid])->scalar();

生成 sql:

select `title` from `post` where `user_id` = 1

直接输出 title 的值。

如果 select(‘title’) 不写的话,生成 sql 是:

`select * from `post` where `user_id`=1`

直接输出 id 的值

表单验证,去除首尾空格:

public function rules()
{
  return [[title', 'content'],'trim']];
}

单独为某个action关闭 csrf 验证

新建一个behavior

use yii;
use yii\base\behavior;
use yii\web\controller;
class nocsrf extends behavior
{
  public $actions = [];
  public $controller;
  public function events()
  {
    return [controller::event_before_action => 'beforeaction'];
  }
  public function beforeaction($event)
  {
    $action = $event->action->id;
    if (in_array($action, $this->actions)) {
      $this->controller->enablecsrfvalidation = false;
    }
  }
}

然后在controller中添加behavior

public function behaviors()
{
  return [
    'csrf' => [
      'class' => nocsrf::classname(),
      'controller' => $this,
      'actions' => [
        'action - name'
      ]
    ]
  ];
}

like 查询 单边加 %

['like', 'name', 'tester'] 会生成 name like ' % tester % '。
['like', 'name', ' % tester', false] => name like ' % tester'
$query = user::find()->where(['like', 'name', $id . ' % ', false]);

sql 随机抽取十名幸运用户

$query = new query;
$query->select('id, city,state,studentname')
  ->from('student')
  ->where(['isactive' => 1])
  ->andwhere(['not', ['state' => null]])
  ->orderby(['rand()' => sort_desc])
  ->limit(10);

关于事务:

yii::$app->db->transaction(function () {
  $order = new order($customer);
  $order->save();
  $order->additems($items);
});
// 这相当于下列冗长的代码:
$transaction = yii::$app->db->begintransaction();
try {
  $order = new order($customer);
  $order->save();
  $order->additems($items);
  $transaction->commit();
} catch (\exception $e) {
  $transaction->rollback();
  throw $e;
}

批量插入数据

第一种方法

$model = new user();
foreach ($data as $attributes) {
  $_model = clone $model;
  $_model->setattributes($attributes);
  $_model->save();
}

第二种方法

$model = new user();
foreach ($data as $attributes) {
  $model->isnewrecord = true;
  $model->setattributes($attributes);
  $model->save() && $model->id = 0;
}

url操作

获取url中的host信息

yii::$app->request->gethostinfo()

获取url中的路径信息(不包含host和参数):

yii::$app->request->getpathinfo()

获取不包含host信息的url(含参数):

# /public/index.php?r=news&id=1
yii::$app->request->url

或者

yii::$app->request->requesturi

只想获取url中的参数部分

# r=news&id=1
yii::$app->getrequest()->querystring;

获取某个参数的值,比如id

yii::$app->getrequest()->getquery('id'); //get parameter 'id'

获取(除域名外的)首页地址

# /public/index.php
yii::$app->user->returnurl;

获取referer

yii::$app->request->headers['referer']

或者

yii::$app->getrequest()->getreferrer()

更多关于yii相关内容感兴趣的读者可查看本站专题:《yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于yii框架的php程序设计有所帮助。