PHP-最轻巧的psr-0兼容自动加载器 [英] PHP - most lightweight psr-0 compliant autoloader

查看:109
本文介绍了PHP-最轻巧的psr-0兼容自动加载器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很小的应用程序,需要一个自动加载器.我可以很容易地使用symfony2类加载器,但这似乎有些过分.

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

那里是否有稳定且轻便的psr-0自动加载程序?

Is there a stable extremely lightweight psr-0 autloader out there?

推荐答案

您要求非常轻巧,让我们这样做;)

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

Timothy Boronczyk编写了一个不错的最小SPL自动加载器: http://zaemis.blogspot.fr/2012/05/writing-minimal-psr-0-autoloader.html

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

我压缩了这样的代码:

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

然后将此[autoload3](的最小版本)与简短的@Alix Axel代码 [autoload4]进行比较:

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最短!

autoload3 is the shortest !

让我们使用稳定的&轻量级(175b!)自动加载器文件:

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

<?php spl_autoload_register(function ($c){preg_match('/^(.+)?([^\\\\]+)$/U',ltrim($c,'\\'),$m);require str_replace('\\','/',$m[1]).str_replace(['\\','_'],'/',$m[2]).'.php';});

也许我疯了,但你要求极端,不是吗?

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

多亏了Alix Axel,我缩短了代码(仅100b!),并使用include而不是require,以防您对旧库有各种自动加载策略(然后在其中使用各种自动加载器) spl自动加载堆栈...).

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...).

<?php spl_autoload_register(function($c){@include preg_replace('#\\\|_(?!.+\\\)#','/',$c).'.php';});

如果您想使其更短/更好,请使用此要点.

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

这篇关于PHP-最轻巧的psr-0兼容自动加载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆