PHP框架-yii2(一)
- yii2的常规安装,使用composer很简单;
- 与之前对yii1的了解,刚接触的yii2变化之一是命名空间的增加,还有就是有些代码的格式有些变化;
细节笔记:
- yii2开发版本基础程序是有注册登陆功能的,字段验证方面较yii1有所进步,可以直接验证某些字段在数据库中是否存在,验证规则如下:
1 public function rules() 2 { 3 return [ 4 [‘username‘, ‘filter‘, ‘filter‘ => ‘trim‘], 5 [‘username‘, ‘required‘], 6 [‘username‘, ‘unique‘, ‘targetClass‘ => ‘\common\models\User‘, ‘message‘ => ‘This username has already been taken.‘],//直接判断用户名在数据库中是否存在 7 [‘username‘, ‘string‘, ‘min‘ => 2, ‘max‘ => 255], 8 9 [‘email‘, ‘filter‘, ‘filter‘ => ‘trim‘], 10 [‘email‘, ‘required‘], 11 [‘email‘, ‘email‘], 12 [‘email‘, ‘unique‘, ‘targetClass‘ => ‘\common\models\User‘, ‘message‘ => ‘This email address has already been taken.‘],//直接判断邮箱在数据库中是否存在 13 14 [‘password‘, ‘required‘], 15 [‘password‘, ‘string‘, ‘min‘ => 6], 16 ]; 17 }
2. 表单生成,格式有所变化。代码如下:
1 <div class="user-register"> 2 <?php $form = ActiveForm::begin([ 3 ‘id‘ => ‘form-register‘, 4 ‘enableAjaxValidation‘=>true,//是否使用ajax验证 5 ‘validateOnSubmit‘=>false]//yii1时虽然使用ajax验证但提交时则不是ajax验证,yii2提交时仍是ajax验证,开启此项代表提交不验证 6 ); ?> 7 <?= $form->field($model, ‘user_login‘)->textInput() ?> 8 <?= $form->field($model, ‘user_pass‘)->passwordInput() ?> 9 <?= $form->field($model, ‘user_nicename‘) ?> 10 <?= $form->field($model, ‘user_email‘) ?> 11 <?= $form->field($model, ‘verifyCode‘)->widget(Captcha::className(), [‘template‘ => ‘<div class="row"><div class="col-lg-2">{input}</div><div class="col-lg-2">{image}</div></div>‘,]) ?> 12 <div class="form-group"> 13 <?= Html::submitButton(‘Submit‘, [‘class‘ => ‘btn btn-primary‘]) ?> 14 </div> 15 <?php ActiveForm::end(); ?> 16 </div><!-- user-register -->
3.yii2的身份验证使用了新的机制,但是没搞懂怎么弄得,我想覆盖都不知道怎么覆盖,密码的加密方式也没搞懂,
4.yii2带了邮箱类,可在main.php的components项中添加配置,代码如下:
//配置代码
‘mailer‘ => [ ‘class‘ => ‘yii\swiftmailer\Mailer‘, ‘transport‘ => [ ‘class‘ => ‘Swift_SmtpTransport‘, ‘host‘ => ‘smtp.163.com‘, ‘username‘ => ‘[email protected]‘, ‘password‘ => ‘*******‘, ‘port‘ => ‘25‘, ‘encryption‘ => ‘tls‘, ], ‘messageConfig‘=>[ ‘charset‘=>‘UTF-8‘, ‘from‘=>[‘[email protected]‘=>‘admin‘] ], ],
//controller控制器中 代码: <?php $mail= Yii::$app->mailer->compose();$mail->setTo(‘[email protected]‘);
$mail->setSubject("邮件测试"); $mail->setTextBody(‘zheshisha ‘); $mail->setHtmlBody("问我我我我我");
if($mail->send()) echo "success"; else echo "failse"; die();
?>
5.yii2中mail的配置useFileTransport为true,只生成邮件,并未发送,应该为false,另外配置文件params.php中supportEmail应设置为邮箱用户名,设置正确的话,重置密码应该就能用了;
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。