lumen 增加组件

Redis

安装composer扩展

composer require predis/predis
composer require illuminate/redis

注入RedisServiceProvider

在目录bootstrap/app.php

$app->register(Illuminate\Redis\RedisServiceProvider::class);

注册Facade

$app->withFacades(true,[
    'Illuminate\Support\Facades\Redis' => 'Redis'
]);

配置ENV

REDIS_HOST=
REDIS_PORT=
REDIS_PASSWORD=

predis其他配置

'read_write_timeout' => 60,   #读写超时时间

使用Redis队列

增加config/queue.php

return [
    'default' => env('QUEUE_DRIVER', 'sync'),
    'connections' => [
        'database' => [
            'driver' => 'database',
            'table' => 'jobs',
            'queue' => 'default',
            'expire' => 60,
        ],
        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
            'queue' => 'default',
            'expire' => 60,
        ],
    ],

    'failed' => [
        'database' => 'mysql', 'table' => 'failed_jobs',
    ],
];

加载配置文件

$app->configure('queue');

设置env

QUEUE_DRIVER=redis

监听队列

php artisan queue:listen

supervisor监听队列

略....

formRequest

直接产考github即可,但是我觉得没必要引入包.. 直接拷贝文件..就好...

以下的代码均为个人习惯

BaseRequest

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use App\Foundation\Services\FormRequest\FormRequest;
use App\Foundation\Services\ApiResponse\ApiResponse;
use Illuminate\Http\Exceptions\HttpResponseException;
class BaseRequest extends FormRequest
{
    /**
     * @var string 当前请求的路由名
     */
    protected $routeName;
    /**
     * BaseRequest constructor.
     */
    public function __construct()
    {
        $this->routeName = get_route_name();
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    protected function failedValidation(Validator $validator)
    {
        $errors = $validator->errors()->toArray();
        throw new HttpResponseException((new ApiResponse())->setMessage(array_first($errors)[0])->setData([
            'errors'=>$errors
        ])->parametersError());
    }
}
/**
 * 获得路由别名
 *
 * @return string
 */
function get_route_name()
{
    return request()->route()[1]['as'];
}

Storage

引入 league/flysystem

composer require league/flysystem

增加配置文件并载入

创建config/filesystems.php

<?php
return [
    'default' => env('FILESYSTEM_DRIVER', 'local'),
    'cloud' => env('FILESYSTEM_CLOUD', 's3'),
    'disks' => [
        'public' => [
            'driver' => 'local',
            'root' => public_path(),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],
]

boostrap/app.php载入配置

$app->configure('filesystems');

测试代码

public function read($path, $bucket = 'public')
{
    return Storage::disk($bucket)->get($path);
}

使用phpredis

phpredis是c编写的扩展, 性能比predis好20%左右吧

安装扩展

# Ubuntu 可以直接apt安装
apt install php-redis

检查是否有扩展

centos 自己安装,或者 源码编译

php -r "phpinfo();"| grep redis

修改lumen config

config->databases.php

'redis' => [
        'client' => 'phpredis',
        ....

这里一定不能注册注册具体的faced

# 下面是错误的示例,一定不能注册.否则会找不到Redis类
$app->withFacades(true,[
    'Illuminate\Support\Facades\Redis' => 'PHPRedis'
]);

# 正确代码
$app->withFacades();

使用Redis

这里可以写一个方法来调用redis

if (!function_exists('redis')) {
    /**
     * redis helpers
     *
     * @param string $connection
     *
     * @return \Illuminate\Redis\Connections\Connection
     */
    function redis($connection = 'default')
    {
        return \Illuminate\Support\Facades\Redis::connection($connection);
    }
}
redis()->set('foo','bar');

phpredis其他属性

'read_timeout' => 30,   #读超时时间
'persistent'=>false,   #是否使用pconnect长连接  默认不使用

dd和dda函数

Redis horizon

cookie

安装Cookie服务提供者

composer require illuminate/cookie

增加session配置

增加 config/session.php

return [
    'driver'          => 'file',
    'lifetime'        => 120,
    'expire_on_close' => false,
    'encrypt'         => false,
    'files'           => storage_path('framework/sessions'),
    'connection'      => 'session',
    'table'           => 'sessions_laravel',
    'store'           => null,
    'lottery'         => [2, 100],
    'cookie'          => 'PHPSESSID',
    'path'            => '/',
    'domain'          => env('SESSION_DOMAIN', null),
    'secure'          => false,
    'http_only'       => true,
];

注册Cookie服务提供者

修改bootstrap/app.php,增加以下内容

// 注册Cookie服务提供者
$app->register(Illuminate\Cookie\CookieServiceProvider::class);
// 加载session配置
$app->configure('session');

测试

use Illuminate\Support\Facades\Cookie;

$router->get('/', function () use ($router) {
    return response($router->app->version())
        ->withCookie(Cookie::make('cookie_key', 'cookie_value'));
});

增加cookie加密,拷贝加密中间件

将laravel下的\app\Http\Middleware\EncryptCookies.php拷贝到lumen同目录下

<?php
namespace App\Http\Middleware;

use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;

class EncryptCookies extends Middleware
{
    /**
     * The names of the cookies that should not be encrypted.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}

生成.env 的app_key

由于lumen是没有 artisan 命令的 不过可以自己 生成一个

str_random(32)

增加全局中间件

$app->middleware([
    ....
    App\Http\Middleware\EncryptCookies::class,
]);

mongodb

安装mongodb扩展

yum install php-mongodb -y

php -m | grep mongodb

php -r "phpinfo();" | grep mongo

安装composer包

composer require jenssegers/mongodb

设置config/database.php

'connections' => [
    .......
    'mongodb' => [
                'driver'   => 'mongodb',
                'host'     => [env('MONGODB_HOST', '127.0.0.1')],
                'port'     => env('MONGODB_PORT', 27017),
                'database' => env('MONGODB_DATABASE','yuyinfang'),
                'username' => env('MONGODB_USERNAME','root'),
                'password' => env('MONGODB_PASSWORD','root'),
    //            'options'  => [
    //                'database' => 'admin' // sets the authentication database required by mongo 3
    //            ]
    //            'options'  => [
    //                'replicaSet' => 'replicaSetName'
    //            ]
            ],
]

设置boostrap/app.php

$app->register(Jenssegers\Mongodb\MongodbServiceProvider::class);
$app->withEloquent();

MongodbServiceProvider 一定要放在 withEloquent 前面否则会报错

Unsupported driver [mongodb]

设置Handle

这一步主要是为了方便调用


<?php
namespace App\Foundation\Services\Mongodb;
use DB;
class Mongodb
{
    /**
     * @param $tables
     *
     * @return \Jenssegers\Mongodb\Eloquent\Builder
     */
    public static function connectionMongodb($tables)
    {
        return DB::connection('mongodb')->collection($tables);
    }
}

设置helper

if (!function_exists('mongodb')) {
    /**
     * @param $table
     *
     * @return \Jenssegers\Mongodb\Eloquent\Builder
     */
    function mongodb($table)
    {
        return \App\Foundation\Services\Mongodb\Mongodb::connectionMongodb($table);
    }
}

使用

mongodb('user')->insert([ 'a'=>1]);

sentry

安装composer

composer require sentry/sentry-laravel

添加配置文件

config/sentry.php

return [
  'dsn' => env('SENTRY_LARAVEL_DSN',''),
];

注册配置文件

$app->configure('sentry');

注册ServiceProvider

$app->register(Sentry\Laravel\ServiceProvider::class);

修改一次

app\Exceptions\Handler.php

public function report(Exception $exception){
   if (app()->bound('sentry') && $this->shouldReport($exception)) {
        app('sentry')->captureException($exception);
   }

   parent::report($exception);
}

测试发送

php artisan sentry:test

延迟队列

$job = (new PlayOrderCompleteJob(Carbon::now()->timestamp))
            ->onQueue('queue:play_order_complete')
            ->delay(Carbon::now()->addMinutes(1));
        dispatch($job);
# 以下这种方式直接60秒后执行也是可以的
$job = (new PlayOrderCompleteJob(Carbon::now()->timestamp))
    ->onQueue('queue:play_order_complete')
    ->delay(60);
dispatch($job);