Configure Namespace and autoload PSR-0

Asked

Viewed 458 times

1

I am developing a project with the following structure: inserir a descrição da imagem aqui

The goal is to make autoload load the classes.

The archive autoload.php:

 function autoload($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');

Abstract class Person

namespace Projeto\Cliente;

use  Projeto\Cliente\Interfaces\ClienteEnderecoInterface;
use  Projeto\Cliente\Interfaces\ClienteImportanciaInterface;

abstract  class Pessoa implements ClienteEnderecoInterface, ClienteImportanciaInterface{}

Interface Clienteenderecointerface

namespace Projeto\Cliente\Interfaces;
interface ClienteEnderecoInterface {}

Customer interface

namespace Projeto\Cliente\Interfaces;
interface ClienteImportanciaInterface {}

Classe Clientepf

namespace Projeto\Cliente\Tipos;
use Projeto\Cliente\Pessoa;
class ClientePF extends Pessoa{}

Classe Clientepj

namespace Projeto\Cliente\Tipos;
use Projeto\Cliente\Pessoa;
class ClientePJ extends  Pessoa {}

Index.php

require_once('./inc/autoload.php');
  $cli = new ClientePF();
  $cli2 = new ClientePJ()

When trying to load the index, php the system informs that it cannot locate the classes:

( ! ) Warning: require(ClientePF.php): failed to open stream: No such file or directory in C:\wamp\www\inc\autoload.php on line 15 Call
Stack
# Time    Memory  Function    Location 1  0.0010  152944  {main}( ) ...\index.php:0 2 0.0030  157944  spl_autoload_call (
) ...\index.php:33 3  0.0030  158000  autoload( ) ...\index.php:33

What should be the correct way to declare namespaces and autoload? Full Code can be downloaded here: Github Given the success of psr-4, I can use it to replace psr-0

  • I think it would make your life easier to use Composer, even if you don’t install dependencies, it would automatically generate autoload for you.

  • And this Source Files folder, the Inc folder is inside it ?

  • The idea is to do without Composer. To learn how to use namespaces

  • Everything is inside this Source Files folder. It’s already a Netbeans structure.

  • Just to learn, fine. But I encourage you to do through PSR-4, by the fact of the depreciation of Zero.

  • If I were to use on PSR-4 as it would look?

  • From what I looked at in the code you are using the pattern closest to the PSR-4, you want to use namespace and underscore classes (for versions made for PHP 5.0 up to 5.2)?

  • I can do psr-4 then. the PHP I’m using is 5.4. I don’t need underscore.

Show 3 more comments

1 answer

2


The PSR-0 other than the PSR-4 supports both _ how much \ to refer to namespaces, of course _ is a namespace simulation that was used until php5.2.

The PSR-0 is out of use as a recommendation, however there are still older libs maintained that use the underscore, to make the simple autoload that follows the PSR-4 would suffice something as explained in this reply /a/91512/3635, take 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 _), thus:

<?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 move up a level of the folder inc, because I believe you will use in the index

About your code:

  1. In PHP for includes I don’t think it’s necessary DIRECTORY_SEPARATOR, in all distros and operating systems that surround perfectly accept /
  2. I didn’t use require, because the problem that should be issued is that of exception class not found, not tested require, but it causes script termination if it does not find the file, which will give an expected error as per the PSR-4 recommendations

Documentation:

Some links that questions and answers on the subject:

  • The psr-0 was not depreciated, as a substitute was the psr-4?

  • Yes @rray is explained in the answer that Linkei, so I explained that it should be used if you need to load an older and maintained lib, the own Composer-autoload does the same yet. They are recommendations and not standards ;) ... thanks, I approved and Linkei some things, if you have something to indicate just let me know that I add the answer.

  • 1

    @rray I think the most appropriate word (if that exists) for the English term deprecated is "obsolete"

  • @Nottherealhemingway is correct.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.