【Laminas】detailActionメソッドからデータを受け取るview側(detail.phtml)を作成する!

Laminas

どーも!marusukeです!

前回の記事(【Laminas】ListControllerにdetailActionメソッドを追加する!)で、ListControllerにdetailActionメソッドを実装し、view側にidと一致するpostデータを渡すようにしました。

ここでは、postデータを受け取りブラウザに表示するview側(detail.phtml)を簡単に作成します!

view側のスクリプト「detail.phtml」を作る!

以下のディレクトリにdetail.phtmlを作ります。

module/Blog/view/blog/list/detail.phtml

<h1>Post Details</h1>

<dl>
    <dt>Post Title</dt>
    <dd><?= $this->escapeHtml($this->post->getTitle()) ?></dd>  // ①

    <dt>Post Text</dt>
    <dd><?= $this->escapeHtml($this->post->getText()) ?></dd>   // ②
</dl>

簡単に説明していきます。(HTML部分の説明は割愛します。)

// ①の部分は以下の2点になります。

  • escapeHtml()というヘルパ関数で、クロスサイトスクリプティング攻撃の無効化
  • $this->post->getTitle()で、ListControllerのdetailActionメソッドから渡されたpostオブジェクトの中のtitleを取得

// ②の部分は以下の2点です。

  • escapeHtml()で、クロスサイトスクリプティング攻撃の無効化
  • $this->post->getText()で、ListControllerのdetailActionメソッドから渡されたpostオブジェクトの中のtextを取得

これでdetailActionメソッドに対応するviewスクリプトdetail.phtmlが出来ました!

ListControllerのdetailActionメソッドを改善する

今の状態は、http://localhost:8080/blog/3のような形で、ブラウザからリクエストすれば、idが3のpostデータの詳細ページが表示されます。

しかしながら、http://localhost:8080/blog/1000のように、idが存在しない場合、ブラウザには以下のようなエラーメッセージを表示させてしまうので、改善します。

An error occurred

An error occurred during execution; please try again later.

Additional information:
InvalidArgumentException

File:
{projectPath}/module/Blog/src/Model/LaminasDbSqlRepository.php:{lineNumber}

Message:
Blog post with identifier "1000" not found.

なので、idが存在しないときは、記事の一覧ページ(http://localhost:8080/blog)に遷移するようにListControllerのdetailActionメソッドを書き直します。

ListControllerのdetailActionメソッドに戻り、以下のように書き直します。

// ListController.php

// ①
use InvalidArgumentException;

// 他のuse文やメソッド部分は割愛します

public function detailAction()
{
    $id = $this->params()->fromRoute('id');
    
    // ②
    try {
        $post = $this->postRepository->findPost($id);
    } catch (\InvalidArgumentException $ex) {
        return $this->redirect()->toRoute('blog');
    }

    return new ViewModel([
        'post' => $post,
    ]);
}

上記のコードを説明します。

// ① use InvalidArgumentException;

例外処理のクラスです。use文にてこのListController.php内で使えるようにします。

// ②の部分

 try {
        $post = $this->postRepository->findPost($id);
 } catch (\InvalidArgumentException $ex) {
        return $this->redirect()->toRoute('blog');
 }

try catch構文のtry部分で、idと一致するpostデータを取得しています。

$post = $this->postRepository->findPost($id);

catch部分で、idと一致するpostデータがなかったときにblog一覧ページに遷移するようにしています。

return $this->redirect()->toRoute('blog');

最後にViewModel()を使って、view側にpostデータを渡す実装をしています。

return new ViewModel([
        'post' => $post,
]);

これでユーザーが、postデータにないidを入力してもblog一覧ページに遷移するようになりました!

お疲れ様でした!

次は、新たなblog記事を追加するために、laminas-formコンポーネントを使い、入力フォームを作っていきます!

コメント

タイトルとURLをコピーしました