Configure Namespace and autoload PSR-0

1

I am developing a project with the following structure:

Thegoalistomakeautoloadloadtheclasses.

Theautoload.phpfile:

functionautoload($className){$className=ltrim($className,'\');$fileName='';$namespace='';if($lastNsPos=strrpos($className,'\')){$namespace=substr($className,0,$lastNsPos);$className=substr($className,$lastNsPos+1);$fileName=str_replace('\',DIRECTORY_SEPARATOR,$namespace).DIRECTORY_SEPARATOR;}$fileName.=str_replace('_',DIRECTORY_SEPARATOR,$className).'.php';require$fileName;}spl_autoload_register('autoload');

AbstractPersonClass

namespaceProjeto\Cliente;useProjeto\Cliente\Interfaces\ClienteEnderecoInterface;useProjeto\Cliente\Interfaces\ClienteImportanciaInterface;abstractclassPessoaimplementsClienteEnderecoInterface,ClienteImportanciaInterface{}

ClientEnderecoInterfaceInterface

namespaceProjeto\Cliente\Interfaces;interfaceClienteEnderecoInterface{}

InterfaceImportanceInterface

namespaceProjeto\Cliente\Interfaces;interfaceClienteImportanciaInterface{}

ClientePFClass

namespaceProjeto\Cliente\Tipos;useProjeto\Cliente\Pessoa;classClientePFextendsPessoa{}

ClientePJclass

namespaceProjeto\Cliente\Tipos;useProjeto\Cliente\Pessoa;classClientePJextendsPessoa{}

Index.php

require_once('./inc/autoload.php');$cli=newClientePF();$cli2=newClientePJ()

Whentryingtoloadtheindex,phptellsthesystemthatitcannotfindtheclasses:

(!)Warning:require(ClientePF.php):failedtoopenstream:NosuchfileordirectoryinC:\wamp\www\inc\autoload.phponline15CallStack#TimeMemoryFunctionLocation10.0010152944{main}()...\index.php:020.0030157944spl_autoload_call()...\index.php:3330.0030158000autoload()...\index.php:33

Whatshouldbethecorrectwaytodeclarenamespacesandautoload?FullCodecanbedownloadedhere: GitHub Given the existence of psr-4, I can use it in place of psr-0

    
asked by anonymous 11.10.2016 / 14:21

1 answer

2

PSR-0 other than PSR-4 supports both _ and \ to refer to namespaces, of course _ is a namespace simulation that was used up to php5.2. >

The PSR-0 is deprecated as a recommendation, however there are still older libs maintained that use the underscore, to make the simple autoload following the PSR-4 would suffice something as I explained in this answer link , see the example:

<?php
function myAutoLoader($class)
{
    // Diretório aonde ficam as bibliotecas
    $base_dir = __DIR__ . '/../src/'; //A sua pasta '/src'

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

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

spl_autoload_register('myAutoLoader');

But it is possible to adapt to accept classes with underscore (underline _ ), like this:

<?php
function myAutoLoader($class)
{
    $separador = '_';

    //Verifica se usa \ como separador
    if (strpos($classname, '\') !== false) {
        //Corrige problema no PHP5.3
        $classname = ltrim($classname, '\');

        $separador = '\';
    }

    // Diretório aonde ficam as bibliotecas
    $base_dir = __DIR__ . '/../src/'; //A sua pasta '/src'

    //Transforma namespace (sendo com \ ou _) no caminho do arquivo
    $file = $base_dir . str_replace($separador, '/', $np) . '.php';

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

spl_autoload_register('myAutoLoader');

In case I used __DIR__ . '/../src/' to raise one level of the inc folder, as I believe you will use it in index

About your code:

  • In PHP for the includes I do not think it is necessary DIRECTORY_SEPARATOR , in all distros and operating systems that I fully accept /
  • I have not used require , because the problem that should be issued is exception of class not found, I did not test require , but it causes script termination if it does not find the file, which will give an error expected according to the PSR-4 recommendations
  • Documentation:

    Some links that ask questions and answers on the subject:

    11.10.2016 / 15:13