2017-08-02 52 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