Zend フレームワーク アプリケーションで、次のコードを何度も使用しています。記事が存在するかどうかを確認するために使用されます。action()
そうでない場合、ユーザーには次のエラー メッセージが表示されます。
$article = ArticleQuery::create()->findOneByUrl($this->_getParam('url', ''));
if (!$article) {
$this->getResponse()
->setRawHeader('HTTP/1.1 404 Not Found');
return $this->_forward('error', null, null, array(
'message' => 'Article not found',
));
}
これを独自のメソッドに分解して、すべてのアクションでコードの負荷を軽減する方法を考えていました。
私はこのようなものになりました:
protected function myAction() {
$article = $this->getArticleIfExists($this->_getParam('url', ''));
if ($article == null) {
return;
}
}
protected function getArticleIfExists($url) {
$article = ArticleQuery::create()->findOneByUrl($this->_getParam('url', ''));
if ($article) {
return $article;
} else {
$this->getResponse()
->setRawHeader('HTTP/1.1 404 Not Found');
$this->_forward('error', null, null, array(
'message' => 'Article not found',
));
return nulL;
}
}
if
でケースを削除したいのですがmyAction()
、_forward()
実行を終了することはできません (もちろん、他のアクションを実行する必要があるため)。
別の可能性(他のコントローラーに実装しました)は次のとおりです。
protected function myAction() {
$article = ArticleQuery::create()->findOneByUrl($this->_getParam('url', ''));
if (!$article) {
return $this->notFound('Article does not exist');
}
}
protected function notFound($message) {
$this->getResponse()
->setRawHeader('HTTP/1.1 404 Not Found');
return $this->_forward('error', null, null, array(
'message' => $message,
));
}
繰り返しますがif
、アクションにはこのチェックがあります。すでに以前より良くなっていますが、さらに良くすることはできますか?
どうすればこれを回避できますか? 現在の URL を失わずにそれを行う可能性はありますか? Redirector
もちろん終了できますが、現在の URL が失われます( /controller/myaction/url/hello -> /error/error/message/Article%20not%20found
)