开发者

Should I write flash messages from my models?

Should I write fla开发者_如何学JAVAsh messages in my model, or my controller?

If I do it in the controller, the model will need to pass it the status messages, so if seems more natural to do it in the model.


No, that's not a good idea. Better to use exceptions or some other form of return values.

Here's a better use of models. Let's write a really simple model to retrieve a value from an array based on a key, if it exists:

class MyModel {
    static private $data = array(
        'cat'    => 'hat',
        'cow'    => 'milk',
        'hotdog' => 'icecream',
    );

    static public function getSomeData($string) {
        if (!is_string($string) {
            throw new Exception("Invalid parameter type: " . gettype($string));
        }
        if (!isset(self::$data[$string])) {
            return array(
                'error' => "Could not find '{$string}'!";,
            );
        } else {
            return array(
                'result' => self::$data[$string],
            );
        }
    }
}

Now, here's how you might use that in your controller:

class DataController extends Zend_Controller_Action {

    public function getAction() {
        $search = $this->_getParam('s', '');
        $errors = array();
        $result = array();
        try {
            $model = MyModel::getSomeData($string);
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        if (isset($model['error'])) {
            $errors[] = $model['error'];
        } else if (isset($model['result']) {
            $result[] = $model['result'];
        } else {
            $errors[] = "An unexpected error has occurred.";
        }

        // Now, you either have a result or errors from your model to work with.

    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜