Table of Contents
1、简介
2、基本使用
3、添加自定义Session驱动
Home Backend Development PHP Tutorial [ Laravel 5.2 文档 ] 服务 -- Session

[ Laravel 5.2 文档 ] 服务 -- Session

Jun 23, 2016 pm 01:17 PM

1、简介

由于HTTP驱动的应用是无状态的,所以我们使用Session来存储用户请求信息。Laravel通过干净、统一的API处理后端各种Session驱动,目前支持的流行后端驱动包括 Memcached、 Redis和 数据库。

1.1 配置

Session配置文件位于 config/session.php。默认情况下,Laravel使用的 session驱动为文件驱动,这对许多应用而言是没有什么问题的。在生产环境中,你可能考虑使用 memcached或者 redis驱动以便获取更快的session性能。

session驱动定义请求的Session数据存放在哪里,Laravel可以处理多种类型的驱动:

  • file – session数据存储在  storage/framework/sessions目录下;
  • cookie – session数据存储在经过加密的安全的cookie中;
  • database – session数据存储在数据库中
  • memcached /  redis – session数据存储在memcached/redis中;
  • array – session数据存储在简单PHP数组中,在多个请求之间是非持久化的。

注意:数组驱动通常用于运行测试以避免session数据持久化。

1.2 Session驱动预备知识

数据库

当使用 databasesession驱动时,需要设置表包含 session项,下面是该数据表的表结构声明:

Schema::create('sessions', function ($table) {    $table->string('id')->unique();    $table->text('payload');    $table->integer('last_activity');});
Copy after login

你可以使用Artisan命令 session:table来生成迁移:

php artisan session:tablecomposer dump-autoloadphp artisan migrate
Copy after login

Redis

在Laravel中使用Redis session驱动前,需要通过Composer安装 predis/predis包。

1.3 其它Session相关问题

Laravel框架内部使用 flashsession键,所以你不应该通过该名称添加数据项到session。

如果你需要所有存储的session数据经过加密,在配置文件中设置 encrypt配置为 true。

2、基本使用

访问session

首先,我们来访问session,我们可以通过HTTP请求访问session实例,可以在控制器方法中通过类型提示引入请求实例,记住,控制器方法依赖通过Laravel服务容器注入:

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Http\Controllers\Controller;class UserController extends Controller{    /**     * 显示指定用户的属性     *     * @param  Request  $request     * @param  int  $id     * @return Response     */    public function showProfile(Request $request, $id)    {        $value = $request->session()->get('key');        //    }}
Copy after login

从session中获取数据的时候,还可以传递默认值作为第二个参数到 get方法,默认值在指定键在session中不存在时返回。如果你传递一个闭包作为默认值到 get方法,该闭包会执行并返回执行结果:

$value = $request->session()->get('key', 'default');$value = $request->session()->get('key', function() {    return 'default';});
Copy after login

如果你想要从session中获取所有数据,可以使用 all方法:

$data = $request->session()->all();
Copy after login

还可以使用全局的PHP函数 session来获取和存储session中的数据:

Route::get('home', function () {    // 从session中获取数据...    $value = session('key');    // 存储数据到session...    session(['key' => 'value']);});
Copy after login

判断session中是否存在指定项

has方法可用于检查数据项在session中是否存在。如果存在的话返回 true:

if ($request->session()->has('users')) {    //}
Copy after login

在session中存储数据

获取到session实例后,就可以调用多个方法来与底层数据进行交互,例如, put方法存储新的数据到session中:

$request->session()->put('key', 'value');
Copy after login

推送数据到数组session

push方法可用于推送数据到值为数组的session,例如,如果 user.teams键包含团队名数组,可以像这样推送新值到该数组:

$request->session()->push('user.teams', 'developers');
Copy after login

获取并删除数据

pull方法将会从session获取并删除数据:

$value = $request->session()->pull('key', 'default');
Copy after login

从session中删除数据项

forget方法从session中移除指定数据,如果你想要从session中移除所有数据,可以使用 flush方法:

$request->session()->forget('key');$request->session()->flush();
Copy after login

重新生成Session ID

如果你需要重新生成session ID,可以使用 regenerate方法:

$request->session()->regenerate();
Copy after login

2.1 一次性数据

有时候你可能想要在session中存储只在下个请求中有效的数据,可以通过 flash方法来实现。使用该方法存储的session数据只在随后的HTTP请求中有效,然后将会被删除:

$request->session()->flash('status', 'Task was successful!');
Copy after login

如果你需要在更多请求中保持该一次性数据,可以使用 reflash方法,该方法将所有一次性数据保留到下一个请求,如果你只是想要保存特定一次性数据,可以使用 keep方法:

$request->session()->reflash();$request->session()->keep(['username', 'email']);
Copy after login

3、添加自定义Session驱动

要为Laravel后端session添加更多驱动,可以使用Session门面上的 extend方法。可以在服务提供者的 boot方法中调用该方法:

<?phpnamespace App\Providers;use Session;use App\Extensions\MongoSessionStore;use Illuminate\Support\ServiceProvider;class SessionServiceProvider extends ServiceProvider{    /**     * Perform post-registration booting of services.     *     * @return void     */    public function boot()    {        Session::extend('mongo', function($app) {            // Return implementation of SessionHandlerInterface...            return new MongoSessionStore;        });    }    /**     * Register bindings in the container.     *     * @return void     */    public function register()    {        //    }}
Copy after login

需要注意的是自定义session驱动需要实现 SessionHandlerInterface接口,该接口包含少许我们需要实现的方法,一个MongoDB的实现如下:

<?phpnamespace App\Extensions;class MongoHandler 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) {}}
Copy after login

由于这些方法并不像缓存的 StoreInterface接口方法那样容易理解,我们接下来快速过一遍每一个方法:

  •   open 方法用于基于文件的session存储系统,由于Laravel已经有了一个  file session 驱动,所以在该方法中不需要放置任何代码,可以将其置为空方法。
  • close 方法和 open 方法一样,也可以被忽略,对大多数驱动而言都用不到该方法。
  • read 方法应该返回与给定$sessionId 相匹配的session数据的字符串版本,从驱动中获取或存储session数据不需要做任何序列化或其它编码,因为Laravel已经为我们做了序列化。
  • write 方法应该讲给定 $data 写到持久化存储系统相应的 $sessionId , 例如MongoDB, Dynamo等等。
  • destroy 方法从持久化存储中移除  $sessionId 对应的数据。
  • gc 方法销毁大于给定$lifetime 的所有 session数据,对本身拥有过期机制的系统如 Memcached 和Redis而言,该方法可以留空。

session驱动被注册之后,就可以在配置文件 config/session.php中使用 mongo驱动了。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

How to Register and Use Laravel Service Providers How to Register and Use Laravel Service Providers Mar 07, 2025 am 01:18 AM

Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles