Skip to content

Instantly share code, notes, and snippets.

@sergeliatko
Last active June 21, 2018 16:18
Show Gist options
  • Save sergeliatko/ac2ea7eb3fe676fe5b2d5b6eacc4bc47 to your computer and use it in GitHub Desktop.
Save sergeliatko/ac2ea7eb3fe676fe5b2d5b6eacc4bc47 to your computer and use it in GitHub Desktop.
PSR4 Autoloader
<?php
/**
* PSR-4 Autoloader.
*/
spl_autoload_register( function ( $class ) {
// validate namespace
if (
strncmp(
$namespace = 'Vendor\\Package',#namespace
$class,
$namespace_length = strlen( $namespace )
) !== 0
) {
return;
};
// try to load the file
if ( file_exists(
$file = join(
DIRECTORY_SEPARATOR,
array(
__DIR__,
'src',#sources directory name
str_replace( '\\', DIRECTORY_SEPARATOR, trim( substr( $class, $namespace_length ), '\\' ) )
)
) . '.php'
) ) {
include $file;
}
} );
@sergeliatko
Copy link
Author

sergeliatko commented Jun 21, 2018

PSR-4 autoloader for your packages that uses DIRECTORY_SEPARATOR constant. Just make sure to update the values marked with comments:

  • #namespace
  • #sources directory name

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment