0
0

[オレオレ08] フロントコントローラー

Last updated at Posted at 2023-12-29

解説

前回の問題点でほぼ同じ内容のエントリーポイントを機能の数だけ用意しなければいけないというものがありました。
ほぼ同じということは共通部分が多いということです。共通部分を使いまわす仕組みがあれば1回書くだけで済ますことができます。
今回はフロントコントローラーという仕組みを使ってエントリーポイントを index.php に集約します。

目次

  • .htaccess作成
  • index.php修正
  • create.html修正
  • 不要となったファイルの削除
  • ブラウザで確認

問題点

  • GETパラメータに悪意のある値を埋め込まれる脆弱性がある
  • index.phpに全ての機能を実装するのは非現実的

.htaccess作成

$ cd /opt/project/stampede/
$ touch public/.htaccess
<IfModule mod_rewrite.c>
    DirectoryIndex index.php
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

index.php修正

index.php
// ビュークラスのインスタンス取得
$view = View::getInstance();

/* 以下を追記 */
// GETパラメータ取得
$params = $request->all();

// フォーム画面表示
if ($params['page'] === 'create') {
    $view->display('create.html');
}
// 登録処理(仮)
elseif ($params['page'] === 'store') {
    header('Location: ?page=thanks');
}
// サンクス画面表示
elseif ($params['page'] === 'thanks') {
    $view->display('thanks.html');
}

exit;

create.hyml修正

formタグのaction属性を修正します

create.html
        <main>
            <form class="gy-5" method="post" action="?page=store">
                <div class="mb-3 col-4">
                    <label for="inputEmail1" class="form-label">お名前</label>

不要となったファイルの削除

$ cd /opt/project/stampede/public/
$ rm create.php store.php thanks.php

ブラウザで確認

https://192.168.56.110/stampede/?page=create


前の記事
[オレオレ07] 入力フォームから登録完了画面の流れ
次の記事
[オレオレ09] MVCのC コントローラー

0
0
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
0
0