从Session变量中修剪未定义的索引

时间:2017-08-02 10:51:05

标签: php slim

我第一次使用Slim php框架,到目前为止它一直很出色。我正在使用库来处理用户注册表单上的验证和会话变量来存储输入并在需要时抛出错误。

我收到错误,告诉我我的会话变量没有定义。我很难看到我失败的地方,会话开始于app.php并且存在以下文件:

Validator.php

namespace App\Validation;

use Respect\Validation\Validator as Respect;
use Respect\Validation\Exceptions\NestedValidationException;

class Validator
{
    protected $errors;

    public function validate($request, array $rules)
    {
        foreach ($rules as $field => $rule) {
            try {
                $rule->setName(ucfirst($field))->assert($request->getParam($field));
            } catch (NestedValidationException $e) {
                $this->errors[$field] = $e->getMessages();
            }
        }

        $_SESSION['errors'] = $this->errors;
        return $this;

    }
    public function failed()
    {
        return !empty($this->errors);
    }
}

ValidationErrorsMiddleware.php

namespace App\Middleware;

class ValidationErrorsMiddleware extends Middleware
{
    public function __invoke($request, $response, $next)
    {
        $this->container->view->getEnvironment()->addGlobal('errors', $_SESSION['errors']);
        unset($_SESSION['errors']);

        $response = $next($request, $response);
        return $response;
    }
}

错误一直指向这一行:

$this->container->view->getEnvironment()->addGlobal('errors', $_SESSION['errors']);

我可以看到会话正在被记录但是没有设置isset我想知道它失败的原因吗?

实际错误本身是:Notice: Undefined index: errors in...

更新

app.php

$app->add(new \App\Middleware\ValidationErrorsMiddleware($container));

Middleware.php

namespace App\Middleware;

class Middleware
{
    protected $container;

    public function __construct($container)
    {
        $this->container = $container;
    }
}

2 个答案:

答案 0 :(得分:2)

您可以尝试使用此代码100%正常工作:

?php

namespace App\Middleware;

class OldInputMiddleware extends Middleware
{
    public function __invoke($request, $response, $next)
    {
            /**
            * To prevent Notice: Undefined index: old in app/Middleware/OldInputMiddleware.php on line 16
            */
            if(empty($_SESSION['old'])){
                $_SESSION['old'] = true;
            }

            $this->container->view->getEnvironment()->addGlobal('old', $_SESSION['old']);
            $_SESSION['old'] = $request->getParams();

        $response = $next($request, $response);
        return $response;
    }
}

答案 1 :(得分:0)

添加会话中间件并启动会话:

// Session middleware
$app->add(function (Request $request, Response $response, $next)
{
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    return $next($request, $response);
});