控制器:
class Address extends BaseController
{
//前置操作
protected $beforeActionList = [
'checkPrimaryScope' => ['only' => 'createOrUpdateAddress,getUserAddress']
];
/**
* 获取用户地址信息
* @return UserAddress
* @throws UserException
*/
public function getUserAddress(){
$uid = Token::getCurrentUid();
$userAddress = UserAddress::where('user_id', $uid)
->find();
if(!$userAddress){
throw new UserException([
'msg' => '用户地址不存在',
'errorCode' => 60001
]);
}
return $userAddress;
}
/**
* 更新或者创建用户收获地址
*/
public function createOrUpdateAddress()
{
$validate = new AddressNew();
$validate->goCheck();
$uid = TokenService::getCurrentUid();
$user = User::get($uid);
if(!$user){
throw new UserException([
'code' => 404,
'msg' => '用户收获地址不存在',
'errorCode' => 60001
]);
}
$userAddress = $user->address;
// 根据规则取字段是很有必要的,防止恶意更新非客户端字段
$data = $validate->getDataByRule(input('post.'));
if (!$userAddress )
{
// 关联属性不存在,则新建
$user->address()
->save($data);
}
else
{
// 存在则更新
// fromArrayToModel($user->address, $data);
// 新增的save方法和更新的save方法并不一样
// 新增的save来自于关联关系
// 更新的save来自于模型
$user->address->save($data);
}
return new SuccessMessage();
}
}
service\Token:
/**
* 当需要获取全局UID时,应当调用此方法
*而不应当自己解析UID
*
*/
public static function getCurrentUid()
{
$uid = self::getCurrentTokenVar('uid');
$scope = self::getCurrentTokenVar('scope');
if ($scope == ScopeEnum::Super)
{
// 只有Super权限才可以自己传入uid
// 且必须在get参数中,post不接受任何uid字段
$userID = input('get.uid');
if (!$userID)
{
throw new ParameterException(
[
'msg' => '没有指定需要操作的用户对象'
]);
}
return $userID;
}
else
{
return $uid;
}
}
/**
* 检查操作UID是否合法
* @param $checkedUID
* @return bool
* @throws Exception
* @throws ParameterException
*/
public static function isValidOperate($checkedUID)
{
if(!$checkedUID){
throw new Exception('检查UID时必须传入一个被检查的UID');
}
$currentOperateUID = self::getCurrentUid();
if($currentOperateUID == $checkedUID){
return true;
}
return false;
}
public static function verifyToken($token)
{
$exist = Cache::get($token);
if($exist){
return true;
}
else{
return false;
}
}
UserException:
class UserException extends BaseException
{
public $code = 404;
public $message = '用户不存在';
public $errCode=60000;
}
baseValidate:
//根据数据的规则,参数过滤显示
public function getDataByRule($arrays)
{
if (array_key_exists('user_id',$arrays) | array_key_exists('uid',$arrays)){
//不允许包含user_id或者uid,防止恶意覆盖user_id外键
throw new ParameterException([
'msg'=>'参数中包含有非法的参数名user_id或者uid'
]);
}
$newArray = [];
foreach ($this->rule as $key => $value)
{
$newArray[$key] = $arrays[$key];
}
return $newArray;
}