项目作者: jwill9999

项目描述 :
Create an autoloader in PHP
高级语言: PHP
项目地址: git://github.com/jwill9999/autoloader_php_setup.git
创建时间: 2019-03-11T18:51:39Z
项目社区:https://github.com/jwill9999/autoloader_php_setup

开源协议:

下载


Create an autoloader in PHP



  1. ***** FILE STRUCTURE *****
  2. src/
  3. App/
  4. Main.php
  5. NewNamespace/
  6. Main.php
  7. composer.json
  8. index.php

composer.json

  1. {
  2. }

run composer install

This will generate a series of autoload files.

Add to composer.json file

  1. {
  2. "autoload": {
  3. "psr-4": {
  4. "App\\": "src/App",
  5. "App\\NewNamespace\\": "src/App/NewNamespace"
  6. }
  7. }
  8. }

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

  1. <?php
  2. require __DIR__ . '/vendor/autoload.php';
  3. new App\Main;
  4. 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.