0
0

[オレオレ04] Viewクラスを作る

Last updated at Posted at 2023-12-29

目的

  • htmlとphpのコードを分離して可読性を高める
  • htmlをテンプレート化して可用性を高める
  • htmlspecialchars()でタグの埋め込みを無効化する

目次

  1. Viewクラス作成
  2. htmlテンプレート作成
  3. index.php でViewクラスを使う

Viewクラス作成

$ cd /opt/project/stampede/
$ touch View.php
View.php
<?php

class View
{
    /**
     * 
     * 
     */
    private static $instance = null;

    /**
     * 
     * 
     */
    private $templateDir = '/opt/project/stampede/views/';

    /**
     * コンストラクタ
     * 
     * @return void
     */
    private function __construct()
    {
        
    }

    /**
     * インスタンスを取得する
     * 
     */
    public static function getInstance()
    {
        if (is_null(self::$instance) === true) {
            self::$instance = new self;
        }
        return self::$instance;
    }

    /**
     * 
     * @param  string $template
     * @param  array $params
     * @return void
     */
    public function display(string $template, array $params = [])
    {
        // テンプレートファイル取得
        $filename = $this->templateDir . $template;

        // 出力のバッファリングを有効にする
        ob_start();
        // ファイルを読み込む
        require $filename;
        // 出力用バッファの内容を取得する
        $body = ob_get_contents();
        // 出力用バッファをクリア(消去)し、出力のバッファリングをオフにする
        ob_end_clean();

        // 表示
        echo $body;

        return;
    }
}

htmlテンプレート作成

$ cd /opt/project/stampede/
$ mkdir views
$ touch views/hello.html
hello.html
<h3>Hello <?php echo htmlspecialchars($params['name']); ?></h3>

<div>
    <?php foreach ($params['hoge'] as $item): ?>
    <div><?php echo htmlspecialchars($item); ?></div>
    <?php endforeach; ?>
</div>

index.php でViewクラスを使う

index.php
<?php

ini_set('display_errors', "On");

require_once('/opt/project/stampede/Request.php');
require_once('/opt/project/stampede/View.php');

$request = Request::getInstance();

$view = View::getInstance();

$view->display('hello.html', $request->all());

exit;

次の記事
[オレオレ05] 転章 vendorディレクトリ
前の記事
[オレオレ03] リクエストを処理するクラスを作る

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