Yii2(电商)

jianfly.com 2019-01-31 1840次浏览

yii下载后配置cookieValidationKey

\config\web.php中配置

取消模板布局

$this->layout = false;

判断post请求

if(Yii::$app->request->isPost) {}

获取post数据

$post = Yii::$app->request->post();

方法跳转

$this->redirect(['default/index']);

返回上一页

$this->goback();

结束

Yii::$app->end();

渲染模板

return $this->render("login", ['model' => $model]);

声明规则场景

$this->scenaric = "login";

加载数据并验证

$this->load($data) && $this->validate(); //载入后可以通过$this->rememberMe来获取数据

声明规则

public function rules() { return []; }

判断验证规则是否出错

if(!$this->hasErrors()) {}

查找一条数据

$data = self::find()->where(' adminuser = :user and adminpass = :pass', [":user" => $this->adminuser, ":pass" => md5($this->adminpass)])->one(); //models中使用self

声明session

$session = Yii::$app->session;

设置session_cookie有效时间(用于自动登录)

session_set_cookie_params($lifetime);

设置session值

$session['admin'] = [
    'adminuser' => $this->adminuser,
    'isLogin' => 1,
];

更新数据

$this->updateAll(['logintime' => time(), 'loginip' => ip2long(Yii::$app->request->userIp)], 'adminuser = :user', ['user' => $this->adminuser]);

获取用户ip

Yii::$app->request->userIp

前台url组件

use yii\helpers\Html;
<a href="<?php echo yii\helpers\Url::to(['/index/index']); ?>"></a>

ActivrForm表单组件

use yii\bootstrap\ActiveForm;
<?php $form = ActiveForm::begin([
'fieldConfig' => [
'template' => '{error}{input}',
],
]);
?>
<?php echo $form->field($model, 'adminuser')->textInput(["class" => "span2", "placeholder" => "管理员账号"]); ?>
<?php echo $form->field($model, 'adminpass')->passwordInput(["class" => 'span2', "placeholder" => "管理员密码"]); ?>
<a href = "<?php echo yii\helpers\Url::to(['public/skpassword']); ?>" class="forget">忘记密码</a>
<?php echo $form->field($model, 'rememberMe')->checkbox([
'id' => 'remember-me',
'template' => '<div class="remember">{input}<label for="remember-me">记住我</label></div>'
]);
?>
<?php echo Hml::submiButon('登录', ["class" => "btn-glow primary login"]); ?>
<?php ActiveForm::end(); ?>

移除所有session

Yii::$app->session->removeAll();

移除单个session

Yii::$app->session->remove('loginname');

设置flashSession

Yii::$app->session->setFlash('info', '电子邮件已经发送成功,请查收');

输出flashSession

if (Yii::$app->session->flash('info')) { echo Yii::$app->session->getFlash('info'); }

邮件

邮件配置/config/we.php components内

发邮件

$time = time(); //时间戳
$token = $this->createToken($data['Admin']['adminuser'], $time); //根据用户名和时间戳生成token 
$mailer = Yii::$app->mailer->compose('seekpass', ['adminuser' => $data['Admin']['adminuser'], 'time' => $time, 'token' => $token]); //生成邮件内容
$mailer->setForm('imooc_shop@163.com'); //来着
$mailer->setTo($data['Admin']['adminemail']); //发给
$mailer->setSubject("慕课商城-找回密码"); //主题
$mailer->send(); //发送邮件

生成Token

public function createToken($adminuser, $time) {
return md5( md5($adminuser) . base64_encode(Yii::$app->request->userIp) . md5($time));
}

邮件模板

<p>尊敬的<?php echo $adminuser; ?>,您好:</p>
<p>您的找回密码链接如下:</p>
<?php $url = Yii::$app->urlManager->createAbsoluteUrl(['admin/manage/mailchangepass', 'timestamp' => $time, 'adminuser' => $adminuser, 'token' => $token]); ?>
<p><a href="<?php echo $url; ?>"><?php echo $url; ?></a></p>
<p>该链接5分钟内有效,请勿传递给别人!</p>
<p>该邮件为系统自动发送,请勿回复!</p>

生成绝对路径

Yii::$app->urlManager->createAbsoluteUrl(['admin/manage/mailchangepass', 'timestamp' => $time, 'adminuser' =>$adminuser, 'token' => $token ])
yii\helpers\Url::to(['/index/index']) //生成相对路径

更新数据

$this->updateAll(['adminpass' => md5($this->adminpass)], 'adminuser = :user', [':user' => $this->adminuser]); //在model中,this代表当前model

构造函数

public function init() {}  //构造函数的功能

分页

use yii\data\Pagination;
$model = Admin::find(); //声明model
$count = $model->count(); //总数
$pageSize = Yii::$app->params['pageSize']['manage']; //每页数量
$pager = new Pagination(['totalCount' => $count, 'pageSize' => $pageSize]); //生成pager
$managers = $model->offset($pager->offset)->limit($pager->limit)->all(); //查找数据
return $this->render("managers", ['managers' => $managers, 'pager' => $pager]); //返回页面

/config/params.php 中设置分页数据

echo yii\widgets\LinkPager::widget( ['pagination' => $pager, 'prevPageLabel' => '&#8249;', 'nextPageLabel' => '&#8250;'] ); //输出分页

删除操作(抛出异常)

try {
$cateid = Yii::$app->request->get('cateid'); //get获取id
if ( empty($cateid) ) {
throw new \Exception("参数错误");
}
$data = Category::find()->where('parentid = :pid', [":pid" => $cateid])->one();
if($data) {
throw new \Exception('该分类下有子分类,不允许删除');
}
if(!Category::deleteAll('cataid = :id', [":id" => $cateid]) ) {
throw new \Exception("删除失败");
}
} catch (\Exception $e) {
Yii::$app->session->setFlash('info', $e->getMessage);
}

联表查询

public function getProfile() {
return $this->hasOne(Profile::className(), ['userid' => 'userid']); //声明两张表的联系
}
$model = User::find()->joinWith('profile');
$count = $model->count();

model中声明表名

public static function tableName() {
return "{{%user}}";
}

生成label中中文

public function attributeLabels() {
return [
'username' => '用户名',
'userpass' => '用户密码',
'repass' => '确认密码',
'usermail' => '电子邮箱',
'loginname' => '用户名/电子邮箱'
]
}

事务处理(删除两张表中的内容)

public function actionDel() {
try{
$userid = (int)Yii::$app->request->get('userid');
if( empty($userid) ) {
throw new \Exception();
}
$trans = Yii::$app->db->beginTransaction(); //开始事务
if( $obj = Profile::find()->where('userid = :id', [':id' => $userid])->one() ) {
$res = Profile::deleteAll('userid = :id', [':id' => $userid]); //删除第一张表
if ( empty($res) ) {
throw new \Exception();
}
}
if(!User::deleteAll('userid = :id', [':id' => $userid])) { //删除第二张表
throw new \Exception();
}
$trans->commit(); //事务提交
} catch (\Exception $e) {
if(Yii::$app->db->getTransaction()) {
$trans->rollback(); //事务回滚
}
}
}

对象转数组

use yii\helpers\ArrayHelper;
$cates = self::find()->all();
$cates = ArrayHelper::toArray($cates);

Assets资源包管理

class AppAsset extends AssetBundels
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/main.css',
];
public $js = [
'ja/main.js',
['js/html5shiv.js', 'condition' => 'lte IE9', 'position' => \yii\web\Wiew::POS_HEAD], //条件加载
];
public $depends = [ //依赖
'yii\web\YiiAsse',
'yii\bootstrap\BootstrapAsset',
'yii\bootstrap\BootstrapPluginAsset',
];
}

layout中布局

use app\assets\AppAsset;
 AppAsset::register($this); 
 <?php $this->beginPage(); ?> 
 <html lang="<?php echo Yii::$app->language; ?>" > 
 <meta charset="<?php echoYii::$app->charset; ?>" >
 <?php $this->registerMetaTag(['http-equiv' => 'Content-Type', 'content' => 'text/html; charset=UTF-8']); ?> 
 <title><?php echo Html::encode($this->title); ?></title> 
 <?php $this->head(); ?> 
 <?php $this->beginBody(); ?> 
 <?php echo $content; ?> 
 <?php $this->endBody(); ?> 
 <?php $this->endPage(); ?>

页面中动态注册js

<?php
$js = <<<JS
//js内容
JS;
$this->registerJs($js);
?>
$this->registerCssFile('admin/css/compiled/user-list.css'); //动态注册css文件

NAV组件

use yii\bootstrap\NavBar;
use yii\bootstrap\Nav;
NavBar::begin([
'options' => [
"class" => "top-bar animate-dropdown",
],
]);
echo Nav::widget([
'options' => [ 'class' => 'navbar-nav navbar-left' ],
'items' => [
['label' => '首页', 'url' => ['/index/index']],
!\Yii::$app->user->isGuest? ( ['label' => '我的购物车', 'url' => ['/cart/index']] ) : '',
!\Yii::$app->user->isGuest? ( ['label' => '我的订单', 'url' => ['/order/index']] ) : '',
],
]);
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => [],
]);
NavBar::end();

面包屑导航

use yii\widgets/Breadcrumbs;
<?php
echo Breadcrumbs::widget([
'homeLink' => ['label' => '首页', 'url' => '/admin/default/index'],
'links' => isset($this->params['breadcrumbs'] ) ? $this->param['breadcrumbs'] : [],
]);
?>
<?php
$this->title = '订单列表';
$this->params['breadcrumbs'][] = ['label' => '订单管理', 'url' => ['/admin/order/list']];
$this->params['breadcrumbs'][] = $this->title;
?>