Autoload class PSR4

2

I would like to create a autoload class that follows the PSR4 recommendations and can be used independently of the Composer autoload >.

The application I'm creating will have the following structure:

/root
 |--/src                
      |-- /App
            |-- /Config
            |-- /Controller
            |-- /Model
      |-- /Core
            |-- /Helper
            |-- /lib
                  |-- Autoload.class.php
  |-- /public_html
        |-- ...
  |-- /vendor  
        |-- ...
  |-- index.php      

In future I will integrate new components into my application through Composer but, I would like an autoload class for my application classes.

    
asked by anonymous 08.10.2015 / 23:26

1 answer

4

Following the structure you used, you would just create an event in a .php file that will be included inside the index.php (which should go inside public_html ), note that public_html will be your root server), however this is not an obligation, I'm just following its folder structure.

For this you will have to use spl_autoload_register , the link link - eu I made an example, with some modifications:

<?php
function myAutoLoader($class)
{
    // Diretório aonde ficam as bibliotecas
    $base_dir = __DIR__ . '/src/App/'; //A pasta que conterá os arquivos que serão autocarregados

    //Transforma namespace no caminho do arquivo
    $file = $base_dir . str_replace('\', '/', $class) . '.php';

    // Verifica se o arquivo existe, se existir então inclui ele
    if (is_file($file)) {
        include_once $file;
    }
}

spl_autoload_register('myAutoLoader');

You can put this in (or use include ) within your index.php , or create a file within Core and use include by calling it.

For more details, see this answer: What is spl_autoloader_register in PHP?

Notes on the code

  • Note: Unlike the link I used include_once instead of require , because if the file has already been manually added it is not a class, it will present more errors than it should and the only error that the PSR-4 standard should display is class not defined .

  • Note 2: I used is_file instead of file_existes , because although it is almost impossible even a developer to use your project may end up creating a folder called ./src/App/Controller/foo.php/index.html , of course that this is a user error, but as I said in the other note , the PSR-4 should only display class not set errors (which is the default) however if require tries to call a folder it will display an error as file_exists returns true to directories:

      

    Warning: require (src / App / Controller / foo.php): failed to open stream: No such file or directory in Z: \ www \ project \ server.php on line 22

         

    Fatal error: require (): Failed opening required 'src / App / Controller / foo.php' (include_path = '.') in Z: \ www \ .php on line 22

The reason for this is because it is described here link :

  

Autoloader implementations MUST NOT throw exceptions, should not generate errors of any level, and should not return any value.

    
09.10.2015 / 01:13