创建数据模型
- 在
/app/models
目录下创建基础数据模型文件BaseModel.php
,添加代码:
<?php
use Phalcon\Mvc\Model;
class BaseModel extends Model {
/**
* 重写getSource()获取表名方法, 给表名添加前缀
* @return string|void
*/
public function getSource( $tableName = '' ) {
// 读取前缀配置
$prefix = Config::instance()->get( 'database.prefix', 'ini' );
if ( $tableName == '' ) {
$tableName = parent::getSource();
}
return $prefix . $tableName;
}
/**
* 新增add方法,成功后会返回LastInsertId
* @param $item
*
* @return int
*/
public function add( $item ) {
try {
$this->create( $item );
return $this->getWriteConnection()->lastInsertId( $this->getSource() );
} catch ( Exception $e ) {
}
return 0;
}
}
- 重写函数
getSource
, 自动添加表名前缀。- 新增添加数据函数
add
,将直接返回新增数据行ID。
- 在
/app/models
目录下创建用户数据模型文件User.php
,添加代码:
<?php
/**
* Class User
*/
class User extends BaseModel {
private static $instance;
public static function instance() {
self::$instance = new self();
return self::$instance;
}
/**
* 登录操作
* 根据手机号获取用户信息
* 未找到则新增用户
*
* @param $user_mobile
*
* @return array
* @throws Exception
*/
public function login( $user_mobile ) {
$model = self::findFirstByUserMobile( $user_mobile );
$user = [];
if ( $model ) {
// 检查帐号状态
if ( ! $model->user_status ) {
throw new Exception( '帐号未激活' );
}
// 设置最后登录时间
if ( ! $model->update( [ 'user_uptime' => time() ] ) ) {
throw new Exception( '更新帐号失败' );
}
$user['user_token'] = $model->user_token;
} else {
$user['user_token'] = Authentication::instance()->generateToken();
// 初始化帐号数据
$item = [
'user_mobile' => $user_mobile,
'user_token' => $user['user_token'],
'user_status' => 1, // 创建帐号时自动激活状态
'user_addtime' => time(),
'user_uptime' => time(),
];
if ( ! $this->add( $item ) ) {
throw new Exception( '创建帐号失败' );
}
}
return $user;
}
}
- 每一个数据模型对应一个数据表:
- 数据表命名规则, 使用小写字母或数字,两个单词之前用英文下划线“_”分隔。如非必要,尽量不要以数字开头。
- 使用对应的数据表名,去除表名前缀和下划线,并将以“_”分隔的单词首字母大写,作为数据模型文件名和类名。
- 这里没有严格按照官方文档,对每个字段都预定义一个对应的属性字段。(并不影响使用)
- 函数
login
实现了:
- 验证手机号是否已注册帐号
- 已经注册且状态为激活,更新登陆时间,并返回
user_token
- 未注册,自动创建帐号,并返回
user_token
- 或返回对应错误信息
实现登陆接口
打开 /app/controllers/UserController.php
文件, 完善函数loginAction
:
/**
* 用户登陆
* @throws Exception
*/
public function loginAction() {
// 验证请求方法是否是POST
$this->isPost();
// 验证请求参数
XValidationUser::instance()->login( $this->getPost() );
// 获取登录信息
$user = User::instance()->login( $this->getPost( 'user_mobile' ) );
if ( $user ) {
Output::instance( $this->response )->success( (object) $user );
} else {
Output::instance( $this->response )->fail( '登录失败' );
}
}
到了这一步,函数
loginAction
其实就比较简单了:
- 调用POST请求方法验证函数
- 调用请求参数验证函数
- 调用获取登录信息数据函数
- 输出用户信息(这里只输出了
user_token
字段,可根据实际需要,返回相应的数据)
PS: 这次,我将前面讲的验证模块和数据模块,都改成了单例模式。大家可下载代码查看。
示例代码下载
链接:https://pan.baidu.com/s/1-Myzt8JDQHExjKz2KJxhPQ 密码:l3lh