LoginSignup
20
22

More than 5 years have passed since last update.

PHPでクラスライブラリを再帰的に探索して自動でrequireするオートローダーを書いてみた

Posted at

Composerのおかげで、外部ライブラリの読み込みを気にする必要がなくなった。しかし、自前のライブラリは依然として手作業でrequire_onceしていて、これが面倒のもと。

PHPunitでテストするときも、オートローダーがないと依存関係をいちいち管理しなくてはならず、これも面倒。

実をいうと、「オートローダーのオーバーヘッドってどうよ?」とか思ってたんだけど、Composerを導入した時点でオートローダーに頼ることは決定したわけで、だったら徹底的にオートローディングしたい。

また、クラスのファイルはなるべくディレクトリを階層化して整理したい。

というわけで、再帰的にクラスを探索するオートローダーです。

以下は、現在制作中の新しいミニ・フレームワークのためのものですが、18行目をコメントアウトして、33行目〜35行目を自分の環境に合わせて書き換えれば、そのまま使える……かも(Composerを使っていないなら、15行目も不要)。

autoload.php

<?php
/**
 * 必要なクラスを自動的にロードする
 *
 *
 * @copyright   Tomoyuki Negishi and ZubaPitaTech Y.K.
 * @author      Tomoyuki Negishi <tomoyu-n@zubapita.jp>
 * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
 * @package Min - Minimam INter framework for PHP
 * @version 1.0
 */

// Composerのautoloder呼び出し
$APP_ROOT = dirname(__DIR__);
require_once $APP_ROOT.'/vendor/autoload.php';

// フレームワークの設定ファイルを読み込み
require_once $APP_ROOT.'/etc/conf.php';

/**
 * Classファイルをロードする
 * 
 * @param string $class クラス名
 * @param boolean Classのロードに成功したときtrue、失敗のときfalse
 */
function autoLoadClass($class)
{
    $classFile = $class.'.php';
    $appRoot = dirname(__DIR__);

    // クラスファイルを探索するディレクトリ
    $classDirs = array(
        'lib',
        'model',
        'controller',
    );

    foreach ($classDirs as $dir) {
        if (searchClassInDir("$appRoot/$dir", $classFile)) {
            return true;
        }
    }
    return false;
}


/**
 * リカーシブにディレクトリを探索してClassファイルをロードする
 * 
 * @param string $dir 探索するディレクトリ名
 * @param string $classFile クラスファイル名
 * @param boolean Classのロードに成功したときtrue、失敗のときfalse
 */
function searchClassInDir($dir, $classFile)
{
    $files = glob("$dir/*");
    if (!empty($files)) {
        foreach ($files as $subFilePath) {

            if (is_dir($subFilePath)) {
                if (searchClassInDir($subFilePath, $classFile)) {
                    return true;
                }
            } else {
                $fileName = basename($subFilePath);

                if ($fileName==$classFile) {
                    require_once $subFilePath;
                    return true;
                }
            }
        }
    }
    return false;
}

/**
 * オートローディング関数を登録
 */
spl_autoload_register( "autoLoadClass");


20
22
2

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
20
22