由於 Passport 不停的查詢資料庫, 為了那些效能, 從而使用redis進行快取
特將修改的過程記錄一下. 如有不對的地方, 歡迎各位能夠指出錯誤
- 新增一個
ClientRepository
繼承於Laravel\Passport\ClientRepository
改寫find()
方法
<?php
namespace App\Repositories;
use Illuminate\Support\Facades\Cache;
use Laravel\Passport\ClientRepository AS BaseClientRepository;
use Laravel\Passport\Passport;
class ClientRepository extends BaseClientRepository
{
/**
* Get a client by the given ID.
*
* @param int $id
* @return \Laravel\Passport\Client|null
*/
public function find($id)
{
return Cache::remember("passport:client:{$id}", 86400,
function () use ($id) {
$client = Passport::client();
return $client->where($client->getKeyName(), $id)->first();
}
);
}
}
- 新增一個
TokenRepository
繼承於Laravel\Passport\TokenRepository
改寫find()
方法
<?php
namespace App\Repositories;
use Illuminate\Support\Facades\Cache;
use Laravel\Passport\Passport;
use Laravel\Passport\TokenRepository AS BaseTokenRepository;
class TokenRepository extends BaseTokenRepository
{
/**
* Get a token by the given ID.
*
* @param string $id
* @return \Laravel\Passport\Token
*/
public function find($id)
{
return Cache::remember("passport:token:{$id}", 86400,
function () use ($id) {
return Passport::token()->where('id', $id)->first();
}
);
}
}
- 在
App\Providers
新增PassportServiceProvider
<?php
namespace App\Providers;
use App\Repositories\ClientRepository;
use App\Repositories\TokenRepository;
use Laravel\Passport\PassportServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;
class PassportServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerTokenRepository();
parent::register();
}
/**
* Register the client repository.
*
* @return void
*/
protected function registerClientRepository()
{
$this->app->singleton('Laravel\Passport\ClientRepository', function ($container) {
$config = $container->make('config')->get('passport.personal_access_client');
return new ClientRepository($config['id'] ?? null, $config['secret'] ?? null);
});
}
/**
* Register the client repository.
*
* @return void
*/
protected function registerTokenRepository()
{
$this->app->singleton('Laravel\Passport\TokenRepository', function ($container) {
return new TokenRepository();
});
}
}
- 在
config/app.php
中providers
新增App\Providers\PassportServiceProvider::class
後就可以使用redis進行資料快取了
關於其他的操作, 請根據自己的實際情況去處理, 當前只做最簡單的快取操作.
本作品採用《CC 協議》,轉載必須註明作者和本文連結