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']],
]
]
]
]