yii2框架学习笔记四

yii 验证码使用

1.控制器中配置

public function actions(){
    return [
        'captcha'=>[
            'class'=>'yii\captcha\CaptchaAction',
            'fixedVerifyCode'=>YII_ENV_TEST ? 'testme':null,
        ]
    ]
}

2.在模型中添加验证码的字段
public $verifyCode;
3.添加校验规则

public function rules(){
    return [
        ['verifyCode','captcha']
    ];
}

4.在模板中

<?=$form->filed($model,'verifyCode')->widget(Captcha::className(),[
    'template'=>'<div class="row"><div class="col-log-3">{image}</div><div class="col-lg-6">{input}</div></div>'
])?>

yii\db\Query

yii\db\ActiveQuery


$provider=new ActiveDataProvider([
    'query'=>Post::find(),
    'pagination'=>[
        'pagesize'=>20,
    ],
]);

$posts=$provider->getModels();

Array data provider

yii\data\ArrayDataProvider::$allModels()

$sort;
$pagination


sql data provider

yii\data\SQLData


$qury=new Query();

$provider=new ActiveDataProvider([
    'query'=>$query->form('post')->all(),
    'sort'=>[
        'attributes'=>[
            'id','username','email'
        ]
    ],
    pagination=>[
        'pageSize'=>10
    ]
]);

$posts=$provider->getModels();

$count=Yii::$app->db->createCommand('select count(*) from user where status=:status,[':status'=>1]')->queryScalar();

$dataProvider=new SqlDataProvider([
    'sql'=>'select * from user where status=:status',
    'params'=>[':status'=>1],
    'totalCount'=>$count,
    'sort'=>[
        'attributes'=>[
            'age',
            'name'=>[
                'asc'=>['first_name'=>SORT_ASC,'last_name'=>SORT_ASC],
                'desc'=>['first_name'=>SORT_DESC,'last_name'=>SORT_DESC],
                'default'=>SORT_DESC,
                'label'=>'Name',
            ],
        ],
    ],
    'pagination'=>[
        'pageSize'=>20,
    ],
]);

$models=$dataProvider->getModels();


主题部件

'components'=>[
    'view'=>[
        'theme'=>[
            'pathMap'=>['@app/views'=>'@app\themes\basic'],
            'baseUrl'=>'@web/themes/basic',
        ],
    ],
],


用户认证

yii\web\IndentityInterface

class User extends ActiveRecord implents IdentityInterface{
    public static function findIdentity($id){
        return static::findOne($id);
    }
    public static function findIdentityByAccessToken($token,$type=null){
        return static::findOne(['access_token'=>$token]);
    }
    public function getId(){
        return $this->id;
    }    
    public function getAuthKey(){
        return $this->auth_key;
    }
    
    public function validateAuthKey($authKey){
        return $this->getAuthKey()===$authKey;
    }
}

产生独一无二随机的字符串
Yii::$app->getSecurity()->generateRandomString();


public function beforeSave($insert){
    if(parent::beforeSave($insert)){
        if($this->isNewRecord){
            $this->auth_key=Yii::$app->getSecurity()->generateRandomString()
        }
        return true;
    }
    return false;
}

yii密码处理


1.生成伪随机数

bcrypt
crypt

$hash=Yii::$app->getSecurity()->generatePasswrodHash($password);

if(Yii::$app->getSecurity()->avlidatePassword($password,$hash)){
    
}else{

}

Yii::$app->getSecurity()->generateRandomString();

2.加解密

$encryptedData=Yii::$app->getSecurity()->encrypt($data,$secretKey);
$data=Yii::$app->getSecurity()->decrypty($encryptedData,$secretKey);

3.数据完整性确认

$data=Yii::$app->getSecurity()->hashData($genuineData,$secretKey),
Yii::$app->getSecurity()->validateData($data,$secretKey);

禁用csrf

控制器层

$this->enableCsrfValition

yii框架客户端认证

2.rpc协议

php composer.phar update

nizsheanez/yii2-json-rpc

public function actions(){
    return array(
        'index'=>[
            'class'=>'\nizsheanez\JsonRpc\Action'
        ]
    );
}


$client=new \nizsheanez\JsonRpc\Client('http://url/of/webservice');

$response=$client->someMethod($arg1,$arg2);

yii 缓存

1.片段缓存
<?php
$this->beginCache($id,['duration'=>3600]){
    $this->endCache();
}

?>


demo


$dependency=[
    'class'=>'yii\caching\DbDependency',
    'sql'=>'select max(update_at) from post',
]

if($this->beginCache($id,['dependency'=>$dependency])){
    //在此生成内容
    $this->endCache();
}

yii\wigetFragmentCache::dependency;

yii\caching\Dependency

yii\widget\FramentCache::variation

yii\widget\Fragment\Cache::enabled;

<?php

$this->beginCache($id,['duration'=>3600,'variation'=>[yii::$app->language],'enabled'=>Yii::$app->request->isGet]){
    //生成缓存

$this->endCache();
    
}

?>


demo


if($this->beginCache($id1)){
    //在此生成内容
    echo $this->renderDynamic('return Yii::$App->user->identity->name');
    
    
    
    if($this->beginCache($id2,$options2)){
        //在此生成内容
        $this->endCache();
    }
    //在此生成内容
    $this->endCache();    
}

2.页面缓存

yii\filters\PageCache

public function behaviors(){
    return[
        'class'=>'yii\filters\PageCache',
        'only'=>['index'],
        'duration'=>40,
        'variations'=>[
            \Yii::$app->language,
        ],
        'dependency'=>[
            'calss'=>'yii\caching\DbDependency',
            'sql'=>'select count(*) from post', 
        ]
    ]
}


yii - memache 缓存

1.配置

'components'=>[
    'cache'=>[
        'class'=>'yii\caching\Memcache',
        'servers'=>[
            'host'=>'server1',
            'port'=>11211,
            'weight'=>100,
        ],
        [
            'host'=>'server2',
            'port'=>11211,
            'weight'=>50,
        ]
    ]
]

$data=$cache->get($key);

if($data==false){
    $cache->set($key,$data);
}


Memcache
ApcCache
DbCache


get
set
mget
mset
madd
exists
delete
flush


yii\caching\Cache::keyPrefix

$cache->set($key,$data,45);

yii\caching\FileDependency

demo

$dependency=new \yii\caching\FileDependency(['filename'=>'demo.txt']);

$cache->set($key,$data,30,$dependency);

$data=$cache->get($key);

依赖链

yii\caching\ChianedDependency
yii\cachingDbDependency
GroupDependency

yii 使用redis 缓存

yii2-redis

2.使用redis

retrn[
    'components'=>[
        'redis'=>[
            'calss'=>'yii\redis\Connection',
            'hostname'=>'localhost',
            'port'=>6379,
            'database'=>0,
        ],
        'cache'=>[
            ’calss‘=>'yii\redis\Cache'
        ],
        'session'=>[
            'class'=>'yii\redis\Session',
            'redis'=>[
                'hostname'=>'localhost',
                'port'=>6379,
                'database'=>1,
            ]
        ]
    ]
]


使用缓存组建

使用session 组建


yii\redis\ActiveRecord;

attributes()

::primaryKey()

demo

class Student extends \yii\redis\ActiveRecord{
    public function attributes(){
    
        return ['id','name','address','registration_date'];
    }
    public function getOrders(){
        return $this->hasMany(Order::className(),['customer_id'=>'id']);
    }
    public static function active($query){
        $query->andWhere(['status'=>1]);
    }
}

$customer=new Student();
$customer->attributes=['name'=>'liLy'];
$customer->save();

echo $customer->id;

$customer->Customer::find()->where(['name'=>'test'])->one();
$customer->Customer::find()->active()->all();


restfulurl


1.创建控制器
2.配置url规则

urlManager组建的配置:

'urlManager'=>[
    'enablePrettyUrl'=>true,
    'enableStrictParsing'=>true,
    'showScriptName'=>false,
    'rules'=>[
        ['class'=>'yii\rest\UrlRule','controller'=>'user'],
    ],
]


GET /users:
HEAD /users:
POST /users:
GET /users/234;
HEAD /users/234
PATCH /users/233
DELETE /users/234;
OPTIONS /users/
OPTIONS /users/234


yii\base\Model

public function fields(){
    return[
        'id',
        'email'=>'email_address',
        'name'=>function(){
            return $this->first_name.' '.$this->last_name;
        }
    ]
}


资源
路由

restful api 路由配置 demo

<?php

'urlManager'=>[
    'enablePrettyUrl'=>true,
    'enableStrictParsing'=>true,
    'showScriptName'=>false,
    'rules'=>[
        ['class'=>'yii\rest\UrlRule','controller'=>'user','except'=>['delete','create'],'extraParrerns'=>'['GET search'=>'search']],
    ],
    
]

/*

[
    'PUT,PATCH users/<id>'=>'user/update',
    'DELETE users/<id>'=>'user/delete',
    'GET,HEAD users/<id>'=>'user/view',
    'POST users'=>'user/create',
    'GET,HEAD users'=>'user/index',
    'users/<id>'=>'user/options',
    'users'=>'user/options',
]

*/

?>


yii\rest\Serializer
yii\filters\ContentNegotiator


curl -i -H "Accept:application/json;q=1.0" "http://locahost/users"

yii\web\JsonResponseFormatter

Http base auth

Oauth 2

yii\filters\RateLimitInterface

getRateLimit()
[100,600]

loadAllowance()
saveAllowance()

X-Rate-Limit-Limit:100
X-Rate-Limit-Remaining
X-Rate-Limit-Reset

api 版本号

http://localhost/v2/users;

api/
    common/
        controllers/
            UserController.php
            PostContrller.php
        modles/
            User.php
            Post.php
        modules/
            v1/
                controllers/
                    UserController.php
                    PostController.php
                models/
                    User.php
                    Post.php
                

return [
    'modules'=>[
        'v1'=>[
            'basePath'=>'@app/modules/v1',
        ],
        'v2'=>[
            'basePath'=>'@app/modules/v2'
        ]        
    ],
    'components'=>[
        'urlManager'=>[
            'enablePrettyUrl'=>true,
            'enableStrictParsing'=>true,
            'showScriptName'=>false,
            'rules'=>[
                ['class'=>'yii\rest\UrlRule','controller'=>['v1/user','v1/post']],
                ['class'=>'yii\rest\UrlUule','controller'=>['v2/user','v2/post']],
            ]
        ]
    ]
]                
                


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Yii 2.0 权威指南 本教程的发布遵循 Yii 文档使用许可. 版权所有 2014 (c) Yii Software LLC. 介绍 已定稿 关于 Yii 已定稿 从 Yii 1.1 升级 入门 已定稿 安装 Yii 已定稿 运行应用 已定稿 第一次问候 已定稿 使用 Forms 已定稿 玩转 Databases 已定稿 用 Gii 生成代码 已定稿 更上一层楼 应用结构 已定稿 结构概述 已定稿 入口脚本 已定稿 应用 已定稿 应用组件 已定稿 控制器(Controller) 已定稿 视图(View) 已定稿 模型(Model) 已定稿 过滤器 已定稿 小部件(Widget) 已定稿 模块(Module) 已定稿 前端资源(Asset) 已定稿 扩展(extensions) 请求处理 已定稿 运行概述 已定稿 引导(Bootstrapping) 已定稿 路由(Route)引导与创建 URL 已定稿 请求(Request) 已定稿 响应(Response) 已定稿 Sessions(会话)和 Cookies 已定稿 错误处理 已定稿 日志 关键概念 已定稿 组件(Component) 已定稿 属性(Property) 已定稿 事件(Event) 已定稿 行为(Behavior) 已定稿 配置(Configurations) 已定稿 类自动加载(Autoloading) 已定稿 别名(Alias) 已定稿 服务定位器(Service Locator) 已定稿 依赖注入容器(DI Container) 配合数据库工作 编撰中 数据访问对象(DAO) - 数据库连接、基本查询、事务和模式操作 编撰中 查询生成器(Query Builder) - 使用简单抽象层查询数据库 编撰中 活动记录(Active Record) - 活动记录对象关系映射(ORM),检索和操作记录、定义关联关系 编撰中 数据库迁移(Migration) - 在团体开发中对你的数据库使用版本控制 待定中 Sphinx 待定中 Redis 待定中 MongoDB 待定中 ElasticSearch 接收用户数据 编撰中 创建表单 已定稿 输入验证 编撰中 文件上传 待定中 多模型同时输入 显示数据 编撰中 格式化输出数据 待定中 分页(Pagination) 待定中 排序(Sorting) 编撰中 数据提供器 编撰中 数据小部件 编撰中 主题 安全 编撰中 认证(Authentication) 编撰中 授权(Authorization) 编撰中 处理密码 待定中 客户端认证 待定中 安全领域的最佳实践 缓存 已定稿 概述 已定稿 数据缓存 已定稿 片段缓存 已定稿 分页缓存 已定稿 HTTP 缓存 RESTful Web 服务 已定稿 快速入门 已定稿 资源 已定稿 路由 已定稿 格式化响应 已定稿 授权验证 已定稿 速率限制 已定稿 版本化 已定稿 错误处理 已定稿 测试
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值