yii基础

request

request:
1. 获取数据和设置默认值
Yii::$app->request->get('id', 6);或Yii::$app->request->post('id', 6)
2. 判断请求方式
Yii::$app->request->isGet 或 Yii::$app->request->isPost
3. 获取浏览器用户信息
Yii::$app->request->userIp

response

response:
1. 设置状态码
Yii::$app->response->statusCode = '404'
2. 设置header
Yii::$app->response->headers->add('Pragma', 'no-cache')
Yii::$app->response->headers->set('Pragma', 'max-age=5')
Yii::$app->response->headers->remove('Pragma')
// 跳转
Yii::$app->response->headers->add('location', 'http://maoriaty.top') 或 $this->redirect('http://maoriaty.top', 302);
// 文件下载
Yii::$app->response->headers->add('content-disposition', 'attachment; filename="a.jpg"') 或 Yii::$app->response->sendFile('./robots.txt');

session

session: 根据浏览器cookie中的PHPSESSIONID获取服务器对应session文件里的值
1. 判断session是否开启
Yii::$app->session->isActive
2. 开启session
Yii::$app->session->open()
3. 设置session
Yii::$app->session->set('user', 'Jabin')或Yii::$app->session['user'] = 'Jabin'
4. 获取session
Yii::$app->session->get('user') 或 Yii::$app->session['user']
5. 删除session
Yii::$app->session->remove('user') 或 unset(Yii::$app->session['user'])
6. 关闭session
Yii::$app->session->close();
7. 设置session过期时间
session_set_cookie_params();
// 登陆
public function login($data)
{
$this->scenario = 'login';
if ($this->load($data) && $this->validate()) {
$lifetime = $this->rememberMe ? 24*3600 : 0; // 过期时间
$session = Yii::$app->session;
if ($session->isActive) {
$session->close();
session_set_cookie_params($lifetime);
}
$session['admin'] = [
'adminuser' => $this->adminuser,
'isLogin' => 1
];
$this->updateAll(['logintime' => time(), 'loginip' => ip2long(Yii::$app->request->userIP)], 'adminuser = :user', [':user' => $this->adminuser]);
return (bool)$session['admin']['isLogin'];
}
return false;
}

cookie

cookie: 浏览器中的cookie值是通过配置中的cookieValidationKey值进行加密过的
1. 添加cookie
Yii::$app->response->cookies->add(new \yii\web\Cookie(['name' => 'user', 'value' => 'Jabin']));
2. 删除cookie
Yii::$app->response->cookies->remove('user');
3. 获取cookie和设置默认值
Yii::$app->request->cookies->getValue('user', 'maoriaty'); //如果user不存在则使用默认值

 views

views
1. 直接输出
echo '<h1>Jabin</h1>'
2. 没布局的输出
return $this->renderPartial('index, ['user' => $name]);
3. 安全输出
<h1><?=Html::encode($user);?> // 转义
<h1><?=HtmlPurifier::process($user);?> // 过滤js
4. 布局文件输出
类中public layout = 'layout' 或 方法中$this->layout = 'layout',不使用布局$this->layout = false;
return $this->render('test'); // 将test文件放在layout文件的<?=$content;?>中
5. 多布局文件输出
在一个视图中调用:<?=$this->render('test2', ['data' => 'show in test']);?>
6. 数据块覆盖布局文件输出
视图中:
<?php $this->beginBlock('block');?>
<h1>Jabin</h1>
<?php $this->endBlock();?>
布局中:
<?=isset($this->blocks['block']) ? $this->blocks['block'] : '<h1>user</h1>'?>

 data

User::find()->one()
User::find()->all()
User::find()->count()
User::find()->average()/min()/max()/scalar()/column()/exists()/batch()/each()
User::model()->findAllBySql('select * form user'); // User::model() = User
User::model()->findByPk(1);

(new Query())->select()->from()->join()->where()->offset()->limit()->all()
Yii::$app->db->createCommand('select * form user')->query()/queryAll()/queryOne()/queryColum()/queryScalar();
User::find()
->with('orders.address')->all(); // 关联查询
public function getProfile()
{
  return $this->hasOne(Profile::className(), ['userid' => 'userid'])->asArray(); // 如果1对多,则使用hasMany()
}
1. 关联查询会把查询结果缓存下来,可以使用unset($user->profile)进行删除
2. 多次查询,使用with()减少查询次数,select * from user where userid in (...),使用with,foreach会直接使用in一次查询出来
where($cond): // 查询条件,使用$cond数组会过滤防止sql攻击 $cond = ['type' => 1, 'status' => 2] $cond = ['id' => [1, 2, 3], 'status' => 2] // id in (1, 2, 3) and atatus = 2 $cond = ['status' => null] where('username = :name or useremail = :email', [':name' => $username, ':email' => $useremail]); CRUD: $user->load($data) && save(); // 新增和修改 Yii::$app->db->createCommand()->insert('user', ['name' => 'test','age' => 30])->execute(); Yii::$app->db->createCommand()->batchInsert('user', ['name', 'age'], [['test01', 30],['test02', 20],['test03', 25]])->execute(); // 批量插入 User::updateAll(['name' => 'Jabin'], ['age' => 40]); Yii::$app->db->createCommand()->update('user', ['age' => 40], 'name = test')->execute(); User::find()->where()->one()->delete(); User::deleteAll(['username' => 'Jabin']); User::deleteByPk(1); Yii::$app->db->createCommand()->delete('user', 'age = 30')->execute(); // 案例优化, 使用asArray()转化为数组,内存占用少,或使用批量查询,减少内存占有量
Test::find()->where(['id' => 1])->all()
Test::find()->where(['>', 'id', 0])->all()
Test::find()->where(['between', 'id', 1, 2])->all()
Test::find()->where(['like', 'title', 'title'])->asArray()->all()
foreach (Test::find()->batch(100) as $tests){ //每次拿100条放入内存
  print_r(count($tests));
}
Test::deleteAll('id > :id', [':id' => 0])
验证:$test = new Test; $test->validate(), $test->hasErrors();$test->save()

transaction

$transaction = Yii::$app->db->beginTransaction();
try{
    $res = $model->deleteAll($cond);
    if(!$res)
        throw new \Exception('操作失败!');
    
    $rt = $relation->deleteAll(['polymeric_id'=>$cond['id']]);
    if(!$rt)
        throw new \Exception('操作失败!');
    
    $transaction->commit(); 
    return Helper::arrayReturn(['status'=>true]);
}
catch (\Exception $e){ $transaction->rollBack(); return Helper::arrayReturn(['status'=>false,'msg'=>$e->getMessage()]); }

 rules

[['字段名1','字段名2'],required, 'message' => '提示信息', 'on' => '场景scenario设置']
['email', 'email'];
['description', 'safe'];
['字段名', 'unique']
['verificationCode', 'captcha'];
['repassword', 'compare', 'compareAttribute' => 'password','message'=>'两次输入的密码不一致!'],
['primaryImage', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024*1024*1024]
[['username', 'email'], 'filter', 'filter' => 'trim', 'skipOnArray' => true];
[['字段名'],'match','pattern'=>'正则表达式','message'=>'提示信息'];
['website', 'url', 'defaultScheme' => 'http'];
['age', 'default', 'value' => null];
['字段名', 'exist'];
['level', 'in', 'range' => [1, 2, 3]];
['age', 'integer'];
['salary', 'number'];
['salary', 'double'];
[['from', 'to'], 'date'];
['username', 'string', 'length' => [4, 24]];
['字段名', 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => true];
['primaryImage', 'image', 'extensions' => 'png, jpg', 'minWidth' => 100, 'maxWidth' => 1000,  'minHeight' => 100, 'maxHeight' => 1000]
[['ids', 'product_ids'], 'each', 'rule' => ['integer']]

['password', 'validatePassword'], // 自定义
public function validatePassword($attribute, $params)
{
    if (!$this->hasErrors()) {
        $user = $this->getUser();
        if (!$user || !$user->validatePassword($this->password)) {
            $this->addError($attribute, '账号或者密码错误!');
        }
    }
}

场景在方法中设置:$this->scenario = 'login';

tableName,attributeLabels

// db.php
<?php
return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=shop',
    'username' => 'root',
    'password' => '123456',
    'charset' => 'utf8',
    'tablePrefix'  => 'shop_'
];
// tableName
<?php
namespace app\models;

use Yii;
use yii\db\ActiveRecord;
use app\models\Profile;

class User extends ActiveRecord
{
    public $repass;
    public $rememberMe;
    public $_user;

    public static function tableName()
    {
        return '{{%user}}'; // %=shop_前缀,对应表shop_user
    }

    public function attributeLabels()
    {
        return [
            'username' => '用户名',
            'userpass' => '用户名密码',
            'useremail' => '用户邮箱',
            'repass' => '重复密码',
            '_user' => '用户名/邮箱'
        ];
    }
}

yii\bootstrap\ActiveForm, yii\helpers\Url, yii\helpers\Html, yii\widgets\Linkpager

// 打印提示信息
<?php
if (Yii::$app->session->hasFlash('info')) {
    echo Yii::$app->session->getFlash('info');
}
?>
// ActiveForm
// 使用$form绑定模型数据
<?php $form = ActiveForm::begin([
    'options' => [
        'class' => 'new_user_form inline-input'
    ],
    'fieldConfig' => [
        'template' => '<div class="span12 field-box">{label}{input}{error}</div>'
    ]
]);?>
<?=$form->field($model, 'cateid')->dropDownList($list);?>
<?=$form->field($model, 'title')->textInput(['class' => 'span9']);?>
<?=$form->field($model, 'description')->textarea(['class' => 'span9 wysihtml5', 'style' => 'margin-left:120px']);?>
<?=$form->field($model, 'issale')->radioList(['0' => '不促销', '1' => '促销'], ['class' => 'span8']);?>
<?=$form->field($model, 'cover')->fileInput(['class' => 'span9']);?>
<?=$form->field($model, 'adminuser')->hiddenInput();?> // 隐藏表单
<?php ActiveForm::end();?>
// 使用input提交数据,提交为: name=>value
<?php $form = ActiveForm::begin([
    'action' => Url::to(['cart/add'])
]);?>
<div class="le-quantity">
    <a class="minus" href="#reduce"></a>
    <input name="productnum" readonly="readonly" type="text" value="1" />
    <a class="plus" href="#add"></a>
</div>
<input type="hidden" name="price" value="<?php echo $product['issale'] == '1'?$product['saleprice']:$product['price'] ?>">
<input type="hidden" name="productid" value="<?php echo $product['productid'] ?>">
<input type='submit' id="addto-cart" class="le-button huge" value="加入购物车">
<?php ActiveForm::end();?>
// Html
<div class="span11 field-box actions">
    <?=Html::submitButton('添加', ['class' => 'btn-glow primary']);?>
    <span>OR</span>
    <?=Html::resetButton('取消', ['class' => 'reset']);?>
</div>
// Url
<a href="<?=Url::to(['product/off', 'productid' => $product->productid]);?>">下架</a>
// 分页
<?=yii\widgets\LinkPager::widget(['pagination' => $pager, 'prevPageLabel' => '&#8249', 'nextPageLabel' => '&#8250']);?>

// 分页数据
$model = Product::find();
$pager = new Pagination(['totalCount' => $model->count(), 'pageSize' => Yii::$app->params['pageSize']['product']]);
$products = $model->offset($pager->offset)->limit($pager->limit)->all();
return $this->render('products', ['products' => $products, 'pager' => $pager]);
// 提示设置
if ($pics && $model->add($post)) {
    Yii::$app->session->setFlash('info', '添加成功');
} else {
    Yii::$app->session->setFlash('info', '添加失败');
}

 

posted @ 2018-07-19 13:08  maoriaty  阅读(193)  评论(0编辑  收藏  举报