I have an application where the user arrives at a page from a link containing an ID value (e.g.: /students/view/42). In my code, I use Zend_Filter_Input, like this:

$input = new Zend_Filter_Input(array(), array(
    'id' => new Zend_Validate_Db_RecordExists(array (
        'table' => 'Students',
        'field' => 'id'
     )
), $this->_request->getParams());
if (!$input->isValid()) {
    // ???
}

I don't think there's anything Earth-shattering going on up to this point. However, what I am unclear about is what to do if the value for the id is invalid.

In his book Zend Framework: A Beginner's Guide, Vikram Vaswani has the user throw an exception (Zend_Controller_Action_Exception('Page Not Found', 404)). Is this the best way to go about handling this, and if not, what other options are available?

有帮助吗?

解决方案

You should redirect user to your page with 404 error description (you should use ErrorController for Exception messages rendering) or to the specific page with the message that such student does not exist.

Just throw exception and render the error page in your ErrorController.

You can do like this:

 $this->getResponse()->setHttpResponseCode(404);

or

throw new Zend_Controller_Action_Exception('This page does not exist', 404);

The typical ErrorController class is the following:

class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');

        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                // 404 error -- controller or action not found
                $this->getResponse()
                     ->setRawHeader('HTTP/1.1 404 Not Found');

                // ... get some output to display...
                break;
            default:
                // application error; display error page, but don't
                // change status code
                break;
        }
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top