1. Go to this page and download the library: Download tomeet/laravel-enum library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Repositories\Enums\IdentityTypeEnum;
use App\Services\AuthorizationService;
use Illuminate\Http\Request;
use Tomeet\Response\Laravel\Support\Facades\Response;
class AuthorizationController extends Controller
{
private AuthorizationService $service;
public function __construct(AuthorizationService $service)
{
$this->middleware('auth:api', ['except' => ['store',]]);
$this->middleware('enum:false');// 请求参数中包含枚举时转换过程中不区分大小写
$this->service = $service;
}
// 假设客户端 POST 方式传入下面参数:(注意,这里 identity_type 传入的值是 email)
/*
{
"identity_type":"email",// 对应 IdentityTypeEnum 中的 EMAIL,这里为小写形式
"account":"[email protected]",
"password":"password",
"remember":false
}
*/
public function store(Request $request)
{
$this->validate($request, [
'identity_type' => '
namespace App\Repositories\Models\MySql;
use App\Repositories\Enums\IdentityTypeEnum;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $casts = [
'identity_type' => IdentityTypeEnum::class
];
}
namespace App\Repositories\Enums;
use Illuminate\Support\Carbon;
use Tomeet\Enum\Laravel\Repositories\Enums\CacheEnum as BaseCacheEnum;
class CacheEnum extends BaseCacheEnum
{
// key => 过期时间计算方法
// 警告:方法名不能相同
const AUTHORIZATION_USER = 'authorizationUser';// 将调用下面定义的 authorizationUser 方法获取缓存过期时间
// ...
// 授权用户信息过期时间定义:将在 Jwt token 过期时一同失效
protected static function authorizationUser($options)
{
$exp = auth('api')->payload()->get('exp'); // token 剩余有效时间
return Carbon::now()->diffInSeconds(Carbon::createFromTimestamp($exp));
}
// ...
}
// app/Providers/EloquentUserProvider.php
public function retrieveById($identifier)
{
// 获取授权用户的缓存 key:类似于 lumen_cache:authorization:user:11
$cacheKey = CacheEnum::getCacheKey(CacheEnum::AUTHORIZATION_USER,$identifier);
// 获取缓存用户缓存的过期时间
$cacheExpireTime = CacheEnum::getCacheExpireTime(CacheEnum::AUTHORIZATION_USER);
return Cache::remember($cacheKey, $cacheExpireTime, function () use ($identifier) {
$model = $this->createModel();
return $this->newModelQuery($model)
->where($model->getAuthIdentifierName(), $identifier)
->first();
});
}