解説
前回のディレクトリ再構成の結果 index.php の require で指定するクラスファイルのパスが長くなってしまいました。長い名前は短いものに比べて憶え辛く脳の負担になります。
また、機能が増えるにつれてファイルを require する機会も増えていくことでしょう。requireは呼び出された時点でファイルを読み込みます。スクリプトの分岐などで結果として読み込む必要のないファイルも読み込むことになります。
このような状況はリソースを消費しパフォーマンスの低下の一因となりかねません。
new したときだけファイルを読み込む。... オートローダーの出番です。
目次
- オートローダークラス作成
- Request.php修正
- View.php修正
- index.php修正
オートローダークラス作成
下記の記事を参考にしました。
オートローダはなぜ名前空間がいいのか
autoLoader.php
<?php
class autoLoader
{
/**
*
* @var string
*/
private $project_root;
/**
*
* @param string $root
* @return void
*/
public function __construct(string $root)
{
$this->project_root = $root;
}
/**
*
*
* @return void
*/
public function register()
{
spl_autoload_register([$this, 'myLoader']);
}
/**
*
*
* @param string $class
* @return bool
*/
public function myLoader(string $class)
{
// 先頭のスラッシュを除く
$className = ltrim($class, '\\');
// バックスラッシュを右に倒す
$className = str_replace('\\', DIRECTORY_SEPARATOR, $className);
// クラス名からファイルのパスを作る
$pattern = '|^App' . DIRECTORY_SEPARATOR . '|';
$replacement = 'app' . DIRECTORY_SEPARATOR;
if (preg_match('|^Stampede|', $className) === 1) {
$pattern = '|^Stampede' . DIRECTORY_SEPARATOR . '|';
$replacement = 'supplier' . DIRECTORY_SEPARATOR . 'stampede' . DIRECTORY_SEPARATOR;
}
$className = preg_replace($pattern, $replacement, $className);
// クラスファイルのパスを作る
$classFileName = $this->project_root . $className . '.php';
// ファイルが読み込める状態でなければfalseを返す
if (is_readable($classFileName) === false) return false;
// ファイルを読み込んでtrueを返す
require_once $classFileName;
return true;
}
}
Request.php修正
Require.php
<?php
namespace Stampede\App\Http; // 追加
class Request
{
// 以下略
View.php修正
View.php
<?php
namespace Stampede\App\Http; // 追加
class View
{
// 以下略
index.php修正
index.php
<?php
ini_set('display_errors', "On");
require_once('../autoLoader.php');
use Stampede\App\Http\Request;
use Stampede\App\Http\View;
// プロジェクトのルートパス
$root = '/opt/project/stampede/';
// オートローダー起動
$autoloader = new autoLoader($root);
$autoloader->register();
// リクエストクラスのインスタンス取得
$request = Request::getInstance();
// ビュークラスのインスタンス取得
$view = View::getInstance();
// テンプレート表示
$view->display('hello.html', $request->all());
exit;