gpt4 book ai didi

php - 如何在 zend 框架中将错误从模型传递到 Controller

转载 作者:可可西里 更新时间:2023-11-01 01:05:10 27 4
gpt4 key购买 nike

我正在使用 zend 框架,这是我的模型和 Controller 方法的骨架

Model Class methods :
_validateRegisterForm($postData)
{
//validating data using Zend_Filter_Input
//Returns instance of Zend_Filter_Input
}

//Return true/false
protected _isNumberAlreadyExists()
{
// I dnt want to perform above validation using zend_validate_db_recordexists
//since i dnt want to mix my dblogic with in buisness logic
}
register($postData)
{
$input=$this->_validateRegisterForm($postData);

if(!$input->isValid())
{
//What should it return to controller
}
if(!$this->_isNumberAlreadyExists($input->number))
{
//What should it return to controller
}
}

controller class api

$this->_model->register($postData)

我希望给定以下条件以相同格式向 Controller 类返回错误

  if(!$input->isValid())
{
//What should it return to controller
}
if(!$this->_isNumberAlreadyExists($input->number))
{
//What should it return to controller
}

我可以简单地从模型类返回 false 但为此我必须保存 zend_filter_Input 实例或错误消息(如果数字已经存在)。因此在那种情况下我必须创建另一个错误处理程序对象,它可以将错误消息转换为通用格式并让 Controller 获取这些错误

对我来说,这看起来不像是在 zend 框架中做事的正确方法。有人愿意帮助我在 zend 框架中将错误从模型传递到 Controller ,还是建议一些其他方法来处理 zend 框架中的错误

最佳答案

开始之前的两个注意事项:

  1. 首先,模型不是一个类,而是一个层。
  2. 下面的代码不是 ZF 特有的

解决你的问题你可以做

public function register()
{
$this->assertThis($postData);
$this->assertThat($postData);

// do something with $postData
}

assertThisassertThat 方法是您的验证方法,只是它们不会返回某些内容,而是抛出适当的异常。 Since register is a Command, it should not return anything at all.

在您的 Controller 中,您只需捕获异常并将它们转换为您的表示层可用的格式(这就是 C+V)

public function registerAction()
{
try {
$this->foo->register($this->getRequest()->whatever());
} catch (ThisException $e) {
// handle here
} catch (ThatException $e) {
// handle here
}
}

另一种选择是收集进行注册的对象内部的任何错误。然后,您当然必须返回并在该对象上提供一个方法来获取错误。所以它会给你的对象增加麻烦。

public function register()
{
if ($something === false) {
$this->errors = 'Something was false';
return false;
}

// do something with $postData
}

然后你的 Controller 会做

public function registerAction()
{
if (false === $this->foo->register($this->whatever())) {
$errors = $this->foo->getErrors();
// do something with $errors
}
}

第三种选择是使用通知模式

An object that collects together information about errors and other information in the domain layer and communicates it to the presentation.

参见 http://martinfowler.com/eaaDev/Notification.html以获得深入的解释。

关于php - 如何在 zend 框架中将错误从模型传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12787549/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com