itxiao6 / session
重写了PHP自带的 SESSION 机制,存储介质支持:本地模式、Memcache、Redis、Mamcached、Xcache,php运行模式支持:LAMP、LNMP、SWOOLE
Installs: 142
Dependents: 1
Suggesters: 0
Security: 0
Stars: 109
Watchers: 3
Forks: 42
Open Issues: 0
Requires
- php: >=5.6.0
- doctrine/cache: ^1.6
This package is auto-updated.
Last update: 2024-12-20 23:19:51 UTC
README
重写了PHP自带的 SESSION 机制,存储介质支持:本地模式、Memcache、Redis、Mamcached、Xcache,php运行模式支持:LAMP、LNMP、SWOOLE
1.引入入口 && 获取实例
use \Itxiao6\Session\SessionManager; $session = \Itxiao6\Session\SessionManager::getSessionInterface();
2.设置驱动
1.本地存储方式(默认)
$session -> set_deiver(new \Doctrine\Common\Cache\FilesystemCache(__DIR__.DIRECTORY_SEPARATOR.'tmp'.DIRECTORY_SEPARATOR));
2.Redis 驱动
$redis = new \Redis(); $redis->connect('127.0.0.1', 6319); $cacheDriver = new \Doctrine\Common\Cache\RedisCache(); $cacheDriver->setRedis($redis); $session -> set_deiver($cacheDriver);
3.Memcache 驱动
$memcache = new \Memcache(); $memcache->connect('127.0.0.1', 11211); $cacheDriver = new \Doctrine\Common\Cache\MemcacheCache(); $cacheDriver->setMemcache($memcache); $session -> set_deiver($cacheDriver);
4.Memcached 驱动
$memcached = new \Memcached(); $memcached->addServer($cacheConfig['Mamcached']['host'], $cacheConfig['Mamcached']['port']); $cacheDriver = new \Doctrine\Common\Cache\MemcachedCache(); $cacheDriver->setMemcached($memcached); $session -> set_deiver($cacheDriver);
5.Xcache 驱动
$session -> set_deiver(new \Doctrine\Common\Cache\XcacheCache());
6.传入配置
$session -> set_config(new \Itxiao6\Session\Tools\Config([ 'session_name'=>'PHPSESSION', 'session_path'=>'/', 'session_id_length'=>32, 'session_id_type'=>1, 'session_storage_prefix'=>'itxiao6_session_', // 默认有效期一天 'session_expire'=>3600*24, ]));
7.启动会话
try{ // 启动会话 $session -> start(); }catch (\Throwable $exception){ // 打印错误 var_dump($exception); }
8.设置值
$session -> session() -> set('name','戒尺');
9.设置值
echo $session -> session() -> get('name');
附录1
SWOOLE 模式使用方式 操作和 驱动和上文使用方法一样,唯一的区别就是 步骤使用1的时候调用的"getSessionInterface" 改为"getSwooleSessionInterface" 并且传入 $request 和 $response
// 创建http server $http = new \swoole_http_server('0.0.0.0', 9501, SWOOLE_BASE); // 监听request 事件 $http->on('request', function(\swoole_http_request $request, \swoole_http_response $response){ /** * 获取Swoole 会话 */ $session = \Itxiao6\Session\SessionManager::getSwooleSessionInterface($request,$response); /** * 设置驱动(文件驱动) */ $session -> set_deiver(new \Doctrine\Common\Cache\FilesystemCache(__DIR__.DIRECTORY_SEPARATOR.'tmp'.DIRECTORY_SEPARATOR)); /** * 设置配置实例 */ $session -> set_config(new \Itxiao6\Session\Tools\Config()); /** * 启动会话 */ try{ $session -> start(); }catch (\Throwable $exception){ var_dump($exception); } /** * 设置一个值 到session 里 */ $session -> session() -> set('user_info',['nickname'=>'戒尺','phone'=>'15538147923','sub'=>['id'=>1]]) -> save(); /** * 获取session 里的一个值 */ $response -> write(json_encode($session -> session() -> get('user_info'))); /** * 结束请求 */ $response -> end(); }); /** * 启动http server */ $http -> start();