Laravel 有几个 Manager 类来管理
基于驱动程序的组件。这些包括缓存、会话、
身份验证和队列组件。经理类负责
用于创建基于特定驱动程序的实现
应用程序的配置。例如,SessionManager 类可以
创建文件、数据库、Cookie 和其他各种实现
会话驱动程序。
这些管理器中的每一个都包含一个可用于
轻松将新的驱动程序解析功能注入到管理器中。
要使用自定义会话驱动程序扩展 Laravel,我们将使用
扩展方法来注册我们的自定义代码:
您应该将会话扩展代码放在 AppServiceProvider 的引导方法中。
实现 SessionHandlerInterface
app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Session;
use Illuminate\Support\ServiceProvider;
use App\Handlers\MyFileHandler;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Session::extend('file', function($app)
{
return new MyFileHandler();
});
}
}
请注意,我们的自定义会话驱动程序应实现SessionHandlerInterface。这个接口只包含我们需要实现的几个简单方法。
app/Handlers/MyFileHandler.php
<?php
namespace App\Handlers;
use SessionHandlerInterface;
class MyFileHandler implements SessionHandlerInterface {
public function open($savePath, $sessionName) {}
public function close() {}
public function read($sessionId) {}
public function write($sessionId, $data) {}
public function destroy($sessionId) {}
public function gc($lifetime) {}
}
或者您可以从 FileSessionHandler 扩展 MyFileHandler 并覆盖相关方法。
扩展 FileSessionHandler
app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Session;
use Illuminate\Support\ServiceProvider;
use Illuminate\Session\FileSessionHandler;
use App\Handlers\MyFileHandler;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Session::extend('file', function($app)
{
$path = $app['config']['session.files'];
return new MyFileHandler($app['files'], $path);
});
}
}
app/Handlers/MyFileHandler.php
<?php
namespace App\Handlers;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Session\FileSessionHandler;
class MyFileHandler extends FileSessionHandler
{
public function __construct(Filesystem $files, $path)
{
parent::__construct($files, $path);
}
}
您可以在扩展框架文档的会话部分找到更多信息。
https://laravel.com/docs/5.0/extending#session