在Laravel 5.1中更改会话文件名

Izy*_*zy- 10 php session laravel-5.1

因此,当有人访问/ storage/framework/sessions文件夹中的网站时,Laravel会保存自己的会话文件.这些会话文件的每个名称都是随机生成的字母数字唯一名称.但是,我想以某种方式重命名文件并为它提供我自己的自定义名称.我有两种选择.

  • 创建会话文件后手动更改文件名(通过创建,复制,替换)
  • 找到随机生成字母数字名称的函数,并使用我自己的方式为每个文件设置唯一名称来更改它(此方法可能会减少并发症)

我的主要目标是将每个用户的会话文件重命名为他们自己的用户ID,该用户ID存储在我的数据库中.所以,名字仍然独一无二,唯一的区别是,我可以通过文件搜索比,如果他们有随机的字母数字名称更容易.

因此,如果有人知道我如何能够采用上述任何一种方法,或者如果你能想到一种更好的方法来实现同样的方法,那就太好了.任何帮助是极大的赞赏!

编辑:决定在这里更新我最终决定做的事情.我决定不使用Laravel生成的内置会话文件,并意识到创建自己的文件更容易,只是让每个客户端访问它.谢谢大家!

Pra*_*aya 1

Laravel 有几个 Manager 类来管理基于驱动程序的组件的创建。其中包括缓存、会话、身份验证和队列组件。管理器类负责根据应用程序的配置创建特定的驱动程序实现。例如,SessionManager 类可以创建文件、数据库、Cookie 和会话驱动程序的各种其他实现。

这些管理器中的每一个都包含一个扩展方法,该方法可用于轻松地将新的驱动程序解析功能注入到管理器中。

要使用自定义会话驱动程序扩展 Laravel,我们将使用扩展方法来注册自定义代码:

您应该将会话扩展代码放置在 AppServiceProvider 的 boot 方法中。

实现SessionHandler接口

应用程序/提供商/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();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我们的自定义会话驱动程序应该实现SessionHandlerInterface。这个接口只包含我们需要实现的一些简单方法。

应用程序/处理程序/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) {}

}
Run Code Online (Sandbox Code Playgroud)

或者您可以从FileSessionHandler扩展 MyFileHandler并重写相关方法。

扩展 FileSessionHandler

应用程序/提供商/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);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

应用程序/处理程序/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);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在扩展框架文档的会话部分找到更多信息。

https://laravel.com/docs/5.0/extending#session