Session & Cookie

    写入 Cookie:

    方法和php原生的 set_cookie 一致。

    Session

    要使用session的话首先需要添加中间件 Cabal\Core\Http\Middleware\EnableSession,在routes.php 中加入以下代码:

    1. use Cabal\Core\Http\Middleware\EnableSession;
    2. //...

    Session 持久化存储依赖缓存服务,所以还要修改 usr/boot.php,取消 Boot 类中的 use Cabal\Core\Cache\ServerHasCache 注释:

    1. $response = new Response();
    2. $session = $request->session();
    3. if ($request->has('username')) {
    4. // 写入
    5. }
    6. $response->getBody()->write(
    7. isset($session['username']) ? ('已登录: ' . $session['username']) : '未登录'
    8. );

    $request->session() 返回的是一个实现了 \Iterator, \ArrayAccess, \Countable, \JsonSerializableCabal\Core\Session 对象,所以你可以和使用 $_SESSION 一样使用它,也可以作为一个对象使用。

    ?> enableSession 中间件会在请求结束前将session中的数据持久化。