Introduction to custom dependency injection examples of lumen in php

黄舟
Release: 2023-03-15 14:18:01
Original
1396 people have browsed it

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



        
Copy after login

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


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(); } }
Copy after login

Then Bind the mapping relationship between the two in bootstrap/app.php:


##

$app->singleton( App\Contracts\TokenHandler::class, App\Services\MysqlTokenHandler::class);
Copy after login

If it is replaced by redis in the future, Just rewrite an implementation of RedisTokenHandler and rebind it, and the specific business logic code does not need to be changed.

So you can directly inject the object instance in the controller, as long as you declare the contract type before the parameters:


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')); } }
Copy after login

You can also get the injection manually in the code An instance of an object, such as:


$currentUser = app(\App\Contracts\TokenHandler::class)->getTokenUser($request->input('api_token'));
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!