我第一次使用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;
}
}
在哪裏驗證集成?你確定驗證功能正在執行嗎? – puelo
請參閱更新 – danjbh
我的意思是實際的Validator類,而不是中間件。也許我是盲目的,但我不明白這個班級是如何融入你的流程的。 – puelo