2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

お手軽簡単PHPでクラスオートローダを作ってみた

Last updated at Posted at 2017-06-22

はじめに

  • PHPを開発するときに、基本的にフレームワークには備わっていると思いますが、クラスをロードするオートローダクラスを作ってみました。
  • 必要最低限の処理しか実装していないですが、それ以上の便利機能も特になさそうなので、よくバッチを作る際とかに重宝していたりしてます。
  • ちなみにオートローダとは、複数ファイルやディレクトリ指定でrequireクラスをしてくれるクラスです。
  • また、同じクラス名が被ってもエラーにならないようにNamespaceをつけられるようにしてます。

ソースコード

AutoLoader.php
<?php

/**
 * オートローダの基底クラスです
 */
class AutoLoader
{
  
    /**
     * @var array $classMap クラスマップ
     */
    protected $classMap = array(
        'XXXX\\Controller\\' => 'app/controller/',
        'XXXX\\Entity\\' => 'app/entity/',
        'XXXX\\Filter\\' => 'app/filter/',
        'XXXX\\Model\\' => 'app/model/',
        'XXXX\\Task\\' => 'tasks/',
        'XXXX\\Test\\' => 'tests/',
        'XXXXLib\\' => 'libs/',
    );
  
    /**
     * 指定した関数を __autoload() の実装として登録する
     */
    public function register()
    {
        spl_autoload_register(array($this, 'loadClass'));
    }
  
    /**
     * 対象となるクラスファイルをロードする
     *
     * @param string $className クラス名称
     * @return なにもしない
     */
    public function loadClass($className)
    {
        $file = str_replace(array_keys($this->classMap), array_values($this->classMap), $className);
  
        if (is_readable(__DIR__ . '/../' . $file . '.php')) {
            require __DIR__ . '/../'. $file . '.php';
            return;
        }
    }
}

使い方

AutoLoaderクラスのロード

require_once ROOT_DIR . '/libs/AutoLoader.php';
$autoLoader = (new AutoLoader())->register();

ロードしたクラスの呼び出し

<?php

namespace XXXX\Controller;

use XXXX\Entity\FugaEntity;
use XXXX\Service\Mysql\FooService;
use XXXXLib\Config;

class BarController
{

全リンク

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?