Skip to content

Instantly share code, notes, and snippets.

@adriengibrat

adriengibrat/l.php

Last active Oct 25, 2019
Embed
What would you like to do?
Extreme minification of shortest possible PSR-0 compliant autoloader, 5 lines !
<?php
//set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__); // optional
spl_autoload_register(function ($class) {
$file = preg_replace('#\\\|_(?!.+\\\)#','/', $class) . '.php';
if (stream_resolve_include_path($file))
require $file;
});
@alixaxel

This comment has been minimized.

Copy link

@alixaxel alixaxel commented Feb 13, 2013

return @include is not making a whole lot of sense in my mind right now.

@alixaxel

This comment has been minimized.

Copy link

@alixaxel alixaxel commented Feb 13, 2013

BUG: \namespace\package_name\Class_Name.

FIX: preg_replace('#\\\\|_(?!.+(?:\\\\|/))#','/',$c);.

Also, it seems that 3 backslashes is enough.

@adriengibrat

This comment has been minimized.

Copy link
Owner Author

@adriengibrat adriengibrat commented Feb 13, 2013

Yeah, i copied the wrong code i think, it's corrected ;)

\namespace\package_name\Class_Name
is resolved as
namespace/package_name/Class/Name.php

About return : I thought returning true could stop the spl autoload stack iteration earlier, but there is no need to do so (spl check if class exists after callink each callback in the stack).

@include (Silent warning) is better than require (Fatal error) because final user could use multiple autolader (with different logic to resolve path) , and we don't know where our autoloader will be in the stack!

@adriengibrat

This comment has been minimized.

Copy link
Owner Author

@adriengibrat adriengibrat commented Nov 15, 2013

@include was lame... Now i check if the file can be included, then require it ;)

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Dec 15, 2013

Why not use require_once? Or does spl_autoload_register automatically prevent loading files multiple times?

@adriengibrat

This comment has been minimized.

Copy link
Owner Author

@adriengibrat adriengibrat commented Feb 8, 2014

Yes, autoloading happens only if the class definition is not yet included. But may be require_once is safer ;)

@victorknust

This comment has been minimized.

Copy link

@victorknust victorknust commented Jul 1, 2014

This regex is reliable?
Some tests indicate an error in this part "(?!".

@makryl

This comment has been minimized.

Copy link

@makryl makryl commented Sep 15, 2014

For the perfect, please add braces to if statement :))
"The body of each structure MUST be enclosed by braces." (c) PSR-2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.