2017-08-02 57 views
0

我第一次使用Slim php框架,迄今为止它一直很棒。我正在使用库来处理用户注册表单和会话变量的验证,以存储输入并在需要时抛出错误。Slim从会话变量中抛出未定义的索引

我得到一个错误,告诉我我的会话变量没有被定义。我挣扎着看到我失败,会话开始开始在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...

UPDATE

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; 
    } 
} 
+0

在哪里验证集成?你确定验证功能正在执行吗? – puelo

+0

请参阅更新 – danjbh

+0

我的意思是实际的Validator类,而不是中间件。也许我是盲目的,但我不明白这个班级是如何融入你的流程的。 – puelo

回答

0

你可以尝试这样的代码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; 
    } 
} 
+0

我想知道为什么而不是压制这个问题。 – danjbh

+0

首先你需要检查会话是否为空if(empty($ _ SESSION ['errors'])){})' –

+0

哪里会是检查这个最好的地方? – danjbh

0

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

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

这可以吗? – danjbh

+0

你在暗示我在做什么? – danjbh

+0

在你的app.php文件中。 – DanielO