Search code examples
phpnamespacesspl-autoload-register

Psr-4 : namespace and spl autoload


Okay, as I browse around there are lots of posts and answers on the line. To my understanding

psr-0: SPL autoload only
psr-4: SPL autoload + namespace

Most of the answers contain LONG methods. psr-4 should not be HARD to implement since it purposes is to simplify file structure yet remaining its own advantage.

I have a structure like this project\view\main.php

in main.php

namespace project\view;
class main {
    .......
}

out of the project folder which is my root directory, i have a index.php

spl_autoload_register( function ($ClassName) {
    require $ClassName . '.php';
});
$main = new project\view\main();

Question: Am I doing it right with psr-4 or am I still missing something from the document?


Solution

  • From the specification PSR-0[1] is deprecated (since 2014-10-21) and is replaced by PSR-4

    From PSR-4 documentation:

    This PSR describes a specification for autoloading classes from file paths. It is fully interoperable, and can be used in addition to any other autoloading specification, including PSR-0. This PSR also describes where to place files that will be autoloaded according to the specification.

    http://www.php-fig.org/psr/psr-4/

    If you want the full rationnale for the specification change you can consult the PSR-4 meta document.

    If you want to see working example, you can search at the same location

    My ultimate recommandation would be to take a look at composer and let it handle it. You would only have to include the automatically generated autoload.php file to have fully functionnal autoloading.