amphp / http-server-session
一个简化应用中会话管理的HTTP服务器插件。轻松处理用户会话,在请求间安全地管理数据。
Requires
- php: >=8.1
- amphp/amp: ^3
- amphp/cache: ^2
- amphp/http: ^2
- amphp/http-server: ^3
- amphp/serialization: ^1
- amphp/sync: ^2
- paragonie/constant_time_encoding: ^2.2
Requires (Dev)
- amphp/php-cs-fixer-config: ^2
- amphp/phpunit-util: ^3
- amphp/redis: ^2
- league/uri: ^6
- phpunit/phpunit: ^9
- psalm/phar: ^5
Suggests
- amphp/redis: Allows storing session data in Redis
Conflicts
- amphp/redis: <2 || >=3
This package is auto-updated.
Last update: 2024-09-03 20:39:26 UTC
README
AMPHP 是一组为 PHP 设计的事件驱动库,考虑了纤程和并发。本包提供了一个 HTTP 服务器 插件,用于简化应用程序的会话管理。轻松处理用户会话,在请求间安全地管理数据。
安装
此包可以作为 Composer 依赖项安装。
composer require amphp/http-server-session
使用方法
基本使用
从会话中读取数据很简单
$session->get('key'); // will read data stored in key 'key'
注意,如果 key
中的数据未找到,则 get()
将返回 null
。
要写入数据,必须首先 lock()
会话,以确保它不能从任何其他地方写入。
$session->lock(); $session->set('key', $data); $session->commit(); // commits & unlocks
调用 commit()
将将数据存储在会话存储中,并解锁会话。
Session
类的其他重要方法包括
// regenerate the client id $session->regenerate(); // force read from storage $session->read(); // rollback what is `set()` in the session but has not been commit()ed yet $session->rollback(); // destroy the session $session->destroy();
在 RequestHandler 中使用中间件来访问 Session
由于此包是 amphp/http-server
的插件,因此有一个中间件实现,该实现将 Session
实例注入到 Request
的属性中。当使用中间件时,会话可以从属性中访问
use Amp\Http\Server\Request; use Amp\Http\Server\RequestHandler; use Amp\Http\Server\Response; use Amp\Http\Server\Session\Session; class SomeRequestHandler implements RequestHandler { public function handleRequest(Request $request): Response { /** @var Session $session */ $session = $request->getAttribute(Session::class); // any operations on the session // return the response } }
请注意,如果未注册属性 Session::class
,则 getAttribute
将抛出 MissingAttributeError
。
中间件将处理请求/响应中的会话 cookie 的设置和读取,以及请求处理完毕后在会话上释放所有锁。
如果您还没有在 amphp/http-server
中使用中间件,请参阅 如何使用中间件与 amphp/http-server
有关的说明。
这里提供了一个简单的示例 examples/simple.php
。
可以进一步从构造函数中根据四个不同方面配置 SessionMiddleware
SessionFactory
CookieAttributes
- Cookie 名称(默认:
'session'
) - 请求属性(默认:
Session::class
)
使用 CookieAttributes 来配置不同的 cookie 属性,例如过期时间或域名
$cookieAttributes = CookieAttributes::default() ->withDomain('amphp.org') ->withExpiry(new \DateTime('+30 min')) ->withSecure();
使用工厂来创建 Session 实例
会话内部使用 3 个依赖项
KeyedMutex
- 用于跨上下文的同步原语SessionStorage
- 用于读取和写入数据的接口SessionIdGenerator
- 用于生成和验证会话 ID 的接口
可以使用提供的 SessionFactory
容易地构造 Session
实例。
/** @var \Amp\Http\Server\Session\SessionFactory $factory */ $session = $factory->create($clientId);
此库包含两个存储实现
- LocalSessionStorage - 默认
- RedisSessionStorage - 在 Redis 中的存储
以及一个会话 ID 生成器
- Base64UrlSessionIdGenerator
SessionFactory
的构造函数允许配置工厂以使用其他实现,这样后续对 create()
的调用将使用新的注入实现。这在某些场景中可能很有益,包括测试。
贡献
请阅读有关我们的行为准则和向我们提交拉取请求的过程的详细信息,请参阅我们的规则。
安全
如果您发现任何与安全相关的问题,请使用私人安全问题报告者,而不是使用公共问题跟踪器。
许可证
MIT 许可证 (MIT)。有关更多信息,请参阅 LICENSE。