目前,我有一个模型,它有一个名为 getEmails($id=NULL) 的方法。
如果 $id == NULL getEmails() 使用 fetchAll($select)->toArray() 返回电子邮件表中的所有记录。在视图中,我有一个 if 语句,用于检查返回的数组是否为空数组。如果是,它会显示一个错误,让用户知道没有电子邮件可显示,否则它会通过 foreach() 循环来显示所有电子邮件。
在这种情况下,使用 if 语句检查电子邮件数组是否为 emapty 是否正确?或者我应该以另一种方式做?
如果 $id != NULL getEmails 使用以下代码仅返回一条记录:
$select->where('id=?',$id);
$row = $this->fetchRow($select)
if(!$row) throw new Exception('Could not find email with ID '.$id);
else return $row->toArray();
如您所见,如果找不到该记录,它将引发异常。
我觉得有一种更统一的方式可以在必要时向用户显示错误。
如果找不到 id $id 的电子邮件,抛出异常是否正确?
我正在努力学习“正确”的做事方式,所以感谢您的帮助:-)
Currently, I have a model that has a method called getEmails($id=NULL).
If $id == NULL getEmails() uses fetchAll($select)->toArray() to return all the records in the email table. In the view I have an if statement that checks to see if the array returned is an empty array. If it is, it displays an error letting the user know that there are no emails to display, otherwise it goes through a foreach() loop to display all the emails.
In this case, is it correct to be using the the if statement to check if the email array is emapty? Or should I be doing it another way?
If $id != NULL getEmails uses the following code to return just one record:
$select->where('id=?',$id);
$row = $this->fetchRow($select)
if(!$row) throw new Exception('Could not find email with ID '.$id);
else return $row->toArray();
As you can see, it throws an exception if the record could not be found.
I feel like there is a more unified way of displaying errors to the user when necessary.
Is it correct to throw an exception in the event that email with id $id cannot be found?
I'm trying to learn the "proper" way of doing things so thank you for all your help :-)
发布评论
评论(1)
您可以使用 Zend Framework Flash Messenger 向用户显示该错误消息。
在控制器中,您可以使用以下代码:
要显示消息,您可以执行以下操作:
在控制器中,您必须检索消息:
在视图脚本中,您要显示它们:
这是如何使用的非常基本的示例闪电信使,但这肯定会让你上路。
编辑:重新阅读你的问题后,我意识到(我应该立即意识到)你正在从模型中生成错误/异常。您可以在控制器中测试 null 返回值并从那里发送消息,或者您可以创建一个会话并将消息存储在其中,以便控制器拾取并放入 flash Messenger 中。
You could use the Zend Framework Flash Messenger to display that error message to the user.
In the controller you could use the following code:
To display the message you could do the following:
In the controller you have to retrieve the messages:
In the view script you want to display them:
This is a VERY basic example of how to use the flash messenger, but this would certainly get you on your way.
EDIT: After re-reading your question I realized (as I should have immediately) you were generating the error/exception from the model. You could test for null return value in the controller and send the message from there or you could create a session and store messages in there to be picked up and put into the flash messenger by the controller.