PHP - most lightweight psr-0 compliant autoloader

后端 未结 7 825
猫巷女王i
猫巷女王i 2020-12-01 09:55

I have a tiny application that i need an autoloader for. I could easily use the symfony2 class loader but it seems like overkill.

Is there a stable extremely lightw

7条回答
  •  醉梦人生
    2020-12-01 10:08

    You ask extremely lightweight, let's do so ;)

    Timothy Boronczyk wrote a nice minimal SPL autoloader : http://zaemis.blogspot.fr/2012/05/writing-minimal-psr-0-autoloader.html

    I condensed the code like this:

    function autoload1( $class ) {
        preg_match('/^(.+)?([^\\\\]+)$/U', ltrim( $class, '\\' ), $match ) );
        require str_replace( '\\', '/', $match[ 1 ] )
            . str_replace( [ '\\', '_' ], '/', $match[ 2 ] )
            . '.php';
    }
    

    Then compare (minified versions of) this [autoload3] with short @Alix Axel code [autoload4] :

    function autoload3($c){preg_match('/^(.+)?([^\\\\]+)$/U',ltrim($c,'\\'),$m);require str_replace('\\','/',$m[1]).str_replace(['\\','_'],'/',$m[2]).'.php';}
    function autoload4($c){require (($n=strrpos($c=ltrim($c,'\\'),'\\'))!==false?str_replace('\\','/',substr($c,0,++$n)):null).str_replace('_','/',substr($c,$n)).'.php';}
    

    autoload3 is the shortest !

    Let's use stable & extremely lightweight (175b !) autoloader file :

    Maybe i'm crazy but you Asked for extreme, no?

    EDIT: Thanks to Alix Axel, i've shorten the code (only 100b !) and used include instead of require in case you have various autoloading strategy for old libs (and then various autoloader in spl autoload stack...).

    If you want to make it shorter / better, please use this gist.

提交回复
热议问题