24
23

More than 5 years have passed since last update.

シンプルなPSR-0準拠クラスオートローダー

Last updated at Posted at 2012-05-27

require_onceの嵐から解放されましょう。
オートローダーの実装はZend_Loader_AutoloaderやSplClassLoaderなどたくさんあるけど、ゴテゴテしてよくわからない機能がついているコードが多い印象。
include_pathをきちんと調整してあれば、PSR-0準拠のクラスは以下のコードでローディングできます。

<?php
//以下、コードの先頭に書いておけば以降require_onceを書かなくてよくなる

function simpleClassLoader($c) {
    $lastSlash = strrpos($c, '\\');
    if (false !== $lastSlash) {
        $lastSlash++;
        $ns = substr($c, 0, $lastSlash);
        $class = substr($c, $lastSlash);
        $path = strtr($ns, '\\', '/') . strtr($class, '_', '/');
    } else {
        $path = strtr($c, '_', '/');
    }
    @include_once $path . '.php';
}

spl_autoload_register('simpleClassLoader');

追記

すみません、PSR-0ってクラス名と名前空間で扱いが異なることを知りませんでした… 正しくは上記になります。

24
23
5

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
24
23