13、Hyperf 3 快速使用 - Session 会话管理的使用

作者: 温新

分类: 【Hyperf 3 基础系列】

阅读: 372

时间: 2023-04-25 12:30:07

hi,我是温新,一名 PHPer

Hypref 版本:Hyperf 3.0

学习目标:掌握 Session 的使用

HTTP 是一种无状态协议,服务器与客户端互不相识,即使客户端是第 2 次或第 N 次,服务器都不认识她是谁。通过 Session 就可以解决他们相不相识的问题。

安装 Session

# 安装
composer require hyperf/session

发布配置文件

生成配置文件

# 配置文件
php bin/hyperf.php vendor:publish hyperf/session

配置文件内容

<?php
// config/autoload/session.php

declare(strict_types=1);
use Hyperf\Session\Handler;

return [
    'handler' => Handler\FileHandler::class,
    'options' => [
        'connection' => 'default',
        'path' => BASE_PATH . '/runtime/session',
        'gc_maxlifetime' => 1200,
        'session_name' => 'HYPERF_SESSION_ID',
        'domain' => null,
        'cookie_lifetime' => 5 * 60 * 60,
    ],
];

驱动配置

Session 组件当前仅适配了两种储存驱动,分别为 文件Redis,默认为 文件 驱动。生产环境中,官方强烈推荐使用 redis 作为存储驱动。

开启 Session

使用 Session 之前,需要在中间件中注册 Session。

<?php
// config/autoload/middlewares.php
    
declare(strict_types=1);

return [
    'http' => [
        \Hyperf\Session\Middleware\SessionMiddleware::class
    ],
];

配置 Session 存储驱动

通过更改配置文件中的 handler 配置修改不同的 Session 储存驱动,而对应 Handler 的具体配置项则由 options 内不同的配置项决定。

文件存储驱动

handler 的值为 Hyperf\Session\Handler\FileHandler 时,说明是文件驱动。所有的 Session 数据文件都会被生成并存储在 options.path 配置值对应的文件夹中,中,默认配置的文件夹为根目录下的 runtime/session 文件夹内。

<?php
// config/autoload/session.php
declare(strict_types=1);

use Hyperf\Session\Handler;

return [
    // 使用文件作为驱动
    'handler' => Handler\FileHandler::class,
    'options' => [
        'connection' => 'default',
        // 数据存储位置
        'path' => BASE_PATH . '/runtime/session',
        'gc_maxlifetime' => 1200,
        'session_name' => 'HYPERF_SESSION_ID',
        'domain' => null,
        'cookie_lifetime' => 5 * 60 * 60,
    ],
];

使用 Redis 驱动

使用 Redis 作为驱动时,需要安装 hyperf/redis 组件。

handler 的值为 Hyperf\Session\Handler\RedisHandler 时,说明是 Redis 驱动。

<?php
// config/autoload/session.php
declare(strict_types=1);
use Hyperf\Session\Handler;

return [
    'handler' => Handler\RedisHandler::class ,
    'options' => [
        'connection' => 'default',
        'path' => BASE_PATH . '/runtime/session',
        'gc_maxlifetime' => 1200,
        'session_name' => 'HYPERF_SESSION_ID',
        'domain' => null,
        'cookie_lifetime' => 5 * 60 * 60,
    ],
];

使用方法

我们准备一个控制器用于操作 Session。

<?php

namespace App\Controller\Test;

use Hyperf\Contract\SessionInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;

#[Controller]
class SessionController
{
    // 注入 Session 对象
    #[Inject]
    private SessionInterface $session;
}

存储数据

方法:set(string $name, $value): void

#[GetMapping('/sessions/set')]
public function set()
{
    $this->session->set('name', '王美丽');
	return 'succ';
}

获取数据

方法:get(string $name, $default = null)

#[GetMapping('/sessions/get')]
public function get()
{
    return $this->session->get('name');
}

获取所有数据

方法:all(): array

#[GetMapping('/sessions/all')]
public function all()
{
    return $this->session->all();
}

判断某个值是否存在

方法:has(string $name): bool

#[GetMapping('/sessions/exists')]
public function exists()
{
    return [
        'result' => $this->session->has('gender')
    ];
}

删除一条数据

方法:remove(string $name)

#[GetMapping('/sessions/remove/{name}')]
public function remove($name)
{
    return [
        'result' => $this->session->remove($name),
    ];
}

返回值:

# 删除一条不存在的数据
{
  "result": null
}
# 删除存在的数据
{
  "result": "王美丽"
}

删除一条或多条数据

方法:forget(string|array $name): void

#[GetMapping('/sessions/forget/{name}')]
public function forget(string | array $name)
{
    // 删除一个
   	#$this->session->forget('foo');
    // 删除多个
 	#$this->session->forget(['foo', 'bar']);
    return [
        'result' => $this->session->forget($name),
    ];
}

获取当前 Session ID

方法:getId(): string

#[GetMapping('/sessions/getid')]
public function getId()
{
    return $this->session->getId();
}

清空当前 Session 数据

方法:clear(): void

#[GetMapping('/sessions/clear')]
public function clear()
{
    return [
        'result' => $this->session->clear(),
    ];
}
请登录后再评论