Skip to content

Instantly share code, notes, and snippets.

@jwill9999
Last active March 11, 2019 18:50
Show Gist options
  • Save jwill9999/33d15492438ef249fa7a08a067494f31 to your computer and use it in GitHub Desktop.
Save jwill9999/33d15492438ef249fa7a08a067494f31 to your computer and use it in GitHub Desktop.
Autoloader

Create an autoloader in PHP

Guidelines

***** FILE STRUCTURE *****

src/
  App/
    Main.php 
	NewNamespace/
		Main.php   
composer.json
index.php

composer.json

{

}

run composer install

This will generate a series of autoload files.

Add to composer.json file

{
"autoload": {
		"psr-4": {
			"App\\": "src/App",
			"App\\NewNamespace\\": "src/App/NewNamespace"
		}
	}
}

This represents the autoloader type "psr-4" plus the key is the namespace and the value is the src/App folder. Here it will autoload all the namespace App files.

run composer dump-autoload

This will generate the autoloader files needed for this to work. Then in index.php :

index.php

<?php

require __DIR__ . '/vendor/autoload.php';

new App\Main;
new App\NewNamespace\Main;

Here we import the autoloader file so we can import all the namespace App classes. Here we then new up the class Main within the namespace App.

Each time a new namespace autoloader is added to composer.json you are required to again run composer dump-autoload again so these changes can be installed.

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