Laravel有几个管理器类来管理基于驱动程序的组件的创建。这些包括缓存、会话、身份验证和队列组件。管理器类负责根据应用程序的配置创建特定的驱动程序实现。例如,SessionManager类可以创建文件、数据库、Cookie和各种其他会话驱动程序的实现。
每个管理器都包括一个扩展方法,可用于轻松地将新的驱动程序解析功能注入到管理器中。
要使用自定义会话驱动程序扩展Laravel,我们将使用extend方法来注册自定义代码:
您应该将会话扩展代码放置在AppServiceProvider的boot方法中。
实现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