【Web】オレオレフレームワークを作ってみる~Smatyとコントローラー編~

プログラミング PHP Web

【Web】オレオレフレームワークを作ってみる~Smatyとコントローラー編~

ここんところ、コロナの影響でネットワークのトラフィックが上昇している模様です。
仕方ないか。
他国よりは全然マシだろうけど。

それよりも、食料。
他国からの輸入に頼り切りの日本。他国は、自国からの輸出量を減らしてきています。
動向に気を付けましょう。

さて、オレオレフレームワークも大枠は仕上げ段階に突入しています。
今回はコントローラクラスの作成と、Smartyによる描画。

では、さっそく。


Smartyダウンロード

Smarty本体をダウンロード。
メジャーバージョンは3かな。
Smarty公式サイト


Smarty展開

ダウンロードしたzipファイルを展開する。
あらかじめ作成しておいた「libralies」ディレクトリに展開したファイルたちをぶち込む。

├─bases
├─config
├─controllers
├─datas
├─libralies
│  └─smarty
├─loader
├─models
├─templates
├─tmp
│  └─smarty
└─styles

展開したファイルの「smarty.class.php」「smarty.php」に変更する。


基底コントローラー作成

BaseController.phpをControllerディレクトリに作成する。

<?php
/**
 * BaseController
 * 基本Controllerクラス
 */
class BaseController
{

    /**
     * smarty
     * Smartyテンプレートエンジン
     * @var mixed
     */
    protected $smarty;

    /**
     * __construct
     * コンストラクタ
     * 
     * @return void
     */
    function __construct() {
        $this -> smarty = new \Smarty();
        $this -> smarty -> template_dir = TEMPLATE_DIRECTRY;
        $this -> smarty -> compile_dir = TEMPLATE_COMPILE_DIRECTRY;
    }

    /**
     * __destruct
     * デストラクタ
     * 
     * @return void
     */
    function __destruct() {
        unset($smarty);
    }
}

TestController.php作成

controllersディレクトリTestController.phpを作成する。
先ほど作成した基底クラスを継承する。

<?php
/**
 * TestController
 * テストControllerクラス
 */
class TestController extends BaseController
{

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

    /**
     * __destruct
     * デストラクタ
     * 
     * @return void
     */
    function __destruct() {
        parent::__destruct();
    }

    /**
     * run
     * 基本表示処理
     * 
     * @param  mixed $params
     * @return void
     */
    public function run($params)
    {
        $this->smarty->assign("test", 'テンプレートOK');
        $this->smarty->display("test.tpl");
    }
}

runメソッド内ではSmartyクラスのメソッドを呼び出している。
・assing
意味としては、テンプレート内の変数への割り当て
・display
表示するテンプレートファイルの指定


test.tpl作成

さて、続いて表示されるテンプレートの作成。
ファイル名をtest.tplとして作成。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <title>テストやで~</title>
</head>
<body>
    <p>{$test}</p>
</body>
</html>

「{$test}」はコントローラ内でSmartyクラスに設定して変数。


index.php変更

index.phpの内容を変更する。
変更内容としては、URLからコントローラクラスのインスタンスを作成。
基本のrunメソッドの呼び出しを行う。

// 途中は略

$controller = array_shift($params);

$ret = $class->run($params);

動かして確認

localhost/testにアクセス。

表示OK。
これでオレオレフレームワーク×Smartyの設定は完了。

とりあえず、MVCのうちのVCはいい感じ。


あとは、モデルかな。
モデルの位置づけをどうするか…悩ましいなぁ。

前の記事 次の記事