框架下载地址:http://www.yiiframework.com/download/
选择advanced版本
初始化:项目目录给予读写权限后,打开命令行控制台,切换到项目目录,命令行执行
php init
将自动创建一系列文件:
Yii Application Initialization Tool v1.0
Which environment do you want the application to be initialized in?
[0] Development
[1] Production
Your choice [0-1, or "q" to quit] 0
Initialize the application under 'Development' environment? [yes|no] yes
Start initialization ...
generate backend/config/main-local.php
generate backend/config/params-local.php
generate backend/web/index-test.php
generate backend/web/index.php
generate common/config/main-local.php
generate common/config/params-local.php
generate console/config/main-local.php
generate console/config/params-local.php
generate frontend/config/main-local.php
generate frontend/config/params-local.php
generate frontend/web/index-test.php
generate frontend/web/index.php
generate tests/codeception/config/config-local.php
generate yii
generate cookie validation key in backend/config/main-local.php
generate cookie validation key in frontend/config/main-local.php
chmod 0777 backend/runtime
chmod 0777 backend/web/assets
chmod 0777 frontend/runtime
chmod 0777 frontend/web/assets
chmod 0755 yii
chmod 0755 tests/codeception/bin/yii
... initialization completed.
配置数据库连接
<?php
return [
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2advanced',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]
],
];
迁移数据
php yii migrate
将为我们创建好User表
Yii Migration Tool (based on Yii v2.0.9)
Creating migration history table "migration"...Done.
Total 1 new migration to be applied:
m130524_201442_init
Apply the above migration? (yes|no) [no]:yes
*** applying m130524_201442_init
> create table {{%user}} ... done (time: 0.683s)
*** applied m130524_201442_init (time: 0.811s)
1 migration was applied.
Migrated up successfully.
为User表增加一个openid字段
ALTER TABLE `user` ADD `openid` VARCHAR( 255 ) NOT NULL AFTER `updated_at`
将字段username auth_key password_hash email设置为allow null
创建分类Category、收支Item
http://localhost/finance-web/backend/web/index.php?r=gii
流程:如果用户是首次登录,则为user表插入一条数据,并返回该用户;如果是老用户,并查询到此用户返回。微信小程序将包括用户id等信息缓存到localStorage
创建WechatLogin模型
增加openid的登录方式findByOpenid()方法
创建APIController基类,用于json格式化输出
<?php
namespace frontend\controllers;
use yii\web\Controller;
use Yii;
use yii\web\Response;
class APIController extends Controller
{
//json方法
public function json($data, $code = 1001, $msg = '加载成功') {
Yii::$app->response->format = Response::FORMAT_JSON;
echo \yii\helpers\Json::encode(['code' => $code, 'msg' => $msg, 'data' => $data]);
}
}
创建UserController,用于登录
<?php
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use common\models\WechatLogin;
class UserController extends APIController
{
// 允许外部提交
public $enableCsrfValidation = false;
/**
* Logs in a user.
*
* @return mixed
*/
public function actionLogin()
{
$model = new WechatLogin();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
$this->json(\yii\helpers\ArrayHelper::toArray($model->login()), 1000, '登录成功');
} else {
$this->json([], 404, '登录失败');
}
}
}
创建微信登录Model
<?php
namespace common\models;
use Yii;
use yii\base\Model;
class WechatLogin extends Model {
public $openid;
public $rememberMe = true;
private $_user;
/**
* @inheritdoc
*/
public function rules()
{
return [
['openid', 'safe'],
['rememberMe', 'boolean'],
];
}
public function login()
{
if ($this->validate()) {
Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
return $this->getUser();
} else {
return false;
}
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
protected function getUser()
{
if ($this->_user === null) {
$this->_user = $this->findByOpenid($this->openid);
}
return $this->_user;
}
/**
* 增加openid登录的方式
*/
public function findByOpenid($openid) {
$user = User::findOne(['openid' => $openid]);
if ($user) {
// 如果已经用户存在
return $user;
} else {
$model = new User();
$model->openid = $openid;
$time = time();
$model->created_at = $time;
$model->created_at = $time;
$model->status = User::STATUS_ACTIVE;
if ($model->save()) {
return $model;
}
// 创建这个用户并返回
}
}
}
到此,完成用户登录。
使用Postman测试一下。
url:localhost/finance-web/frontend/web/index.php?r=user/login
param:WechatLogin[openid] = 黄秀杰
response:{"code":1000,"msg":"登录成功","data":{"openid":"黄秀杰","created_at":1475654180,"status":10,"updated_at":1475654180,"id":4}}
实际操作中,发现没有appId,则不能拿到res.code,于是就解析不了openid,所以在微信开放公测之前,姑且拿nickname作为openid使用。
未完待续...
谢谢阅读,希望本文对你有帮助,有问题可以在公众号给我留言交流,订阅号:huangxiujie85