>  기사  >  백엔드 개발  >  Lumen 프레임워크의 사용자 정의 종속성 주입에 대한 간략한 토론

Lumen 프레임워크의 사용자 정의 종속성 주입에 대한 간략한 토론

*文
*文원래의
2018-01-03 16:09:141756검색

이 문서에서는 주로 Lumen 프레임워크의 사용자 정의 종속성 주입에 대해 설명합니다. 편집자님이 꽤 좋다고 하셔서 참고하실 수 있도록 오늘 공유드리고자 합니다. 편집자를 따라 살펴보겠습니다. 모두에게 도움이 되기를 바랍니다.

예를 들어 현재 토큰 인증 시스템을 사용하고 있는데 향후에는 redis로 변경될 수 있습니다.

먼저 계약 파일 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); 
}

을 정의합니다. 여기에 정의된 3가지 방법이 있습니다: 토큰 생성, 토큰에 해당하는 사용자 가져오기, 토큰 삭제.

그런 다음 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(&#39;user_id&#39;, $userId)->count() >= $this->userTokensMax) { 
   Token::where(&#39;user_id&#39;, $userId)->orderBy(&#39;updated_at&#39;, &#39;asc&#39;)->first()->delete(); 
  } 
 
  $token = \Illuminate\Support\Str::random(32); 
  if (!Token::create([&#39;token&#39; => $token, &#39;user_id&#39; => $userId])) { 
   return false; 
  } 
 
  return $token; 
 } 
 
 /** 
  * @inheritdoc 
  */
 public function getTokenUser($token) 
 { 
  $tokenObject = Token::where(&#39;token&#39;, $token)->first(); 
 
  return $tokenObject && $tokenObject->user ? $tokenObject->user : false; 
 } 
 
 /** 
  * @inheritdoc 
  */
 public function removeToken($token) 
 { 
  return Token::find($token)->delete(); 
 } 
}

아래에 app/Services/MysqlTokenHandler.php 구현을 작성합니다. 그런 다음 bootstrap/app.php에서 둘 사이의 매핑 관계를 바인딩합니다.

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

나중에 Redis로 변경하는 경우 새로 작성하면 됩니다. RedisTokenHandler를 구현하고 다시 바인딩하기만 하면 특정 비즈니스 로직 코드를 변경할 필요가 없습니다.

따라서 컨트롤러에 개체 인스턴스를 직접 삽입할 수 있으므로 매개 변수 앞에 계약 유형을 선언하면 됩니다.

public function logout(Request $request, TokenHandler $tokenHandler) 
{ 
 if ($tokenHandler->removeToken($request->input(&#39;api_token&#39;))) { 
  return $this->success([]); 
 } else { 
  return $this->error(Lang::get(&#39;messages.logout_fail&#39;)); 
 } 
}

다음과 같이 코드에 삽입된 개체의 인스턴스를 수동으로 가져올 수도 있습니다.

$currentUser = app(\App\Contracts\TokenHandler::class)->getTokenUser($request->input(&#39;api_token&#39;));

관련 권장 사항 :

Laravel의 대기열 사용하기

laravel 작성 APP 인터페이스(API)

Laravel의 미들웨어 구현 방법 살펴보기

위 내용은 Lumen 프레임워크의 사용자 정의 종속성 주입에 대한 간략한 토론의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.