11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Phalcon Model::save エラーハンドリングのオシャレな書き方

Last updated at Posted at 2014-01-10

Phalcon\Mvc\Model::save は失敗時に例外を投げてくれないので、
bool の返却値を見てハンドリングしなきゃいけません。

Model 基底クラスを作って save メソッドをオーバーライドし、失敗時に例外を投げる方法もあります。
しかしそれだと Controller でエラーメッセージをコントロールしづらいので、今回はそのまま、書き方を工夫します。

イマイチな書き方

$entry = new BlogEntry();
$entry
    ->setDate($date)
    ->setTitle($title)
    ->setBody($body);
if (!$entry->save()) {
    throw new \Exception("ブログ記事の保存に失敗しました");
}

せっかくリズムよくメソッドチェーンをつないでいるのに、save だけ切り離されちゃいます。
かと言って結果を一時変数に格納するのも微妙。。。

シャレオツな書き方

$entry = new BlogEntry();
$entry
    ->setDate($date)
    ->setTitle($title)
    ->setBody($body)
    ->save()
    or throw new \Exception("ブログ記事の保存に失敗しました");

save までコンボをつなげました!

Validation Error 等のエラーメッセージもハンドリングしたい

ControllerBase クラスにエラーハンドリングメソッドを追加します。

ControllerBase.php
class ControllerBase extends Controller
{

	/**
	 * @param \Phalcon\Mvc\Model $model
	 * @param string $message
	 * @param string $method
	 * @param int $line
	 * @param string $indent
	 * @throws \Exception
	 */
	protected function handleSaveError($model, $message, $method = __METHOD__, $line = __LINE__, $indent = "	") {
        $errors = "";
        foreach ($model->getMessages() as $err) {
            $errors .= $indent . $err . "\n";
        }
		$this->logger->error("model save error: {$message} at {$method} on line {$line}\n{$errors}");
		throw new \Exception($message . "\n" . $errors);
	}
}

このように使います。

$entry = new BlogEntry();
$entry
    ->setDate($date)
    ->setTitle($title)
    ->setBody($body)
    ->save()
    or $this->handleSaveError($entry, "ブログ記事の保存に失敗しました");
11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?