Importerクラスというのを作ってみた

require_once dirname( __FILE__) とかを一つ一つ書くのが面倒なので作ったもの。

使い方

<?php
include_once 'Importer.php';

// ソースファイルと同じディレクトリにあるファイルをrequire_onceする
// Importerクラス内でバックトレースを通じて呼び出し側のファイルパスを取得しているので
// いちいちdirname( __FILE__) と書かなくても良い
Importer::create()->import( './hoge.php');

// importメソッドは$thisを返すのでこのように続けて書ける
Importer::create()->import( './fuga.php')->import( './piyo.php');

// 上記と同じことを別の書き方でする
Importer::create()->import( './{fuga,piyo}.php');

// include path内のファイルをrequire_onceする
// これは普通にrequire_onceするのと同じ
Importer::create()->import( 'Net/URL/Mapper.php');

// ソースファイルと同じディレクトリの.php拡張子のファイルをすべてrequire_onceする
Importer::create()->import( '.');

// fooディレクトリの.php拡張子のファイルをすべてrequire_onceする
Importer::create()->import( './foo');

// 同一ディレクトリの.class.php拡張子のファイルのみrequire_onceする
Importer::create()->import( './*.class.php');

*や{}は相対パスでimportした時のみ有効です。

ソース

<?php

class Importer
{
  protected $baseDirName;
  protected function __construct( $file_path)
  {
    $this->baseDirName = dirname( $file_path);
  }
  public static function create()
  {
    $trace = debug_backtrace();
    return new self( $trace[0]['file']);
  }
  public function import( $path)
  {
    if( substr( $path, 0, 1) === '.') {
      if( preg_match( '/\*/', $path))     $this->importAny( $path);
      elseif( preg_match( '/{/', $path))  $this->importAny( $path);
      elseif( $this->isFile( $path))      $this->importRelative( $path);
      elseif( $this->isDir( $path))       $this->importAll( $path);
      else throw new Exception( 'invalid argument: ' . var_export( $path, true));
    }
    else require_once $path;
    
    return $this;
  }
  protected function importAny( $path)
  {
    $list = glob( $this->buildRelativePath( $path), GLOB_BRACE);
    foreach( $list as $path) require_once $path;
  }
  protected function importRelative( $path)
  {
    require_once $this->buildRelativePath( $path);
  }
  protected function importAll( $dir)
  {
    $dir = $this->buildRelativePath( $dir);
    $list = glob( $dir . '/*.php');
    foreach( $list as $path) require_once $path;
  }
  protected function isDir( $path)
  {
    return is_dir( $this->buildRelativePath( $path));
  }
  protected function isFile( $path)
  {
    return is_file( $this->buildRelativePath( $path));
  }
  protected function buildRelativePath( $path)
  {
    return $this->baseDirName . '/' . $path;
  }
}