For example, I now have a token authentication system. Currently, I use mysql token table to implement it. It may be changed to redis in the future. How can I achieve seamless connections in the future?
First define a contract file app/Contracts/TokenHandler.php
<?php namespace App\Contracts; /** * 处理Token的Contracts * @package App\Contracts */ interface TokenHandler { /** * 创建一个token * @param $userId integer 用户Id * @return string */ public function createToken($userId); /** * 得到该token的用户 * @param $token string token值 * @return \App\User 拥有该token的用户 */ public function getTokenUser($token); /** * 删除一个token * @param $token string token值 * @return bool 是否成功 */ public function removeToken($token); }
Three methods are defined here: create token, get the user corresponding to the token, and delete token.
Then we write an implementation app/Services/MysqlTokenHandler.php under Mysql
<?php namespace App\Services; use App\Contracts\TokenHandler; use App\Orm\Token; /** * 处理Token的Contracts对应的Mysql Service * @package App\Services */ class MysqlTokenHandler implements TokenHandler { /** * @var int 一个用户能够拥有的token最大值 */ protected $userTokensMax = 10; /** * @inheritdoc */ public function createToken($userId) { while (Token::where('user_id', $userId)->count() >= $this->userTokensMax) { Token::where('user_id', $userId)->orderBy('updated_at', 'asc')->first()->delete(); } $token = \Illuminate\Support\Str::random(32); if (!Token::create(['token' => $token, 'user_id' => $userId])) { return false; } return $token; } /** * @inheritdoc */ public function getTokenUser($token) { $tokenObject = Token::where('token', $token)->first(); return $tokenObject && $tokenObject->user ? $tokenObject->user : false; } /** * @inheritdoc */ public function removeToken($token) { return Token::find($token)->delete(); } }
Then Bind the mapping relationship between the two in bootstrap/app.php:
##
$app->singleton( App\Contracts\TokenHandler::class, App\Services\MysqlTokenHandler::class);
public function logout(Request $request, TokenHandler $tokenHandler) { if ($tokenHandler->removeToken($request->input('api_token'))) { return $this->success([]); } else { return $this->error(Lang::get('messages.logout_fail')); } }
$currentUser = app(\App\Contracts\TokenHandler::class)->getTokenUser($request->input('api_token'));
The above is the detailed content of Introduction to custom dependency injection examples of lumen in php. For more information, please follow other related articles on the PHP Chinese website!