Chan Chan - 5 months ago 19
PHP Question

How to use __autoload function when use composer load

app/Core
contollers


This is my website structure to put the main class, I user composer
psr-4
rule to import class under
app/Core
folder.

composer.json



{
"autoload": {
"psr-4": {
"Core\\": ["app/Core"]
}
}
}


index.php



<?php

include 'vendor/autoload.php';

new Core/Api; // it's work


It works fine, but I want to autoload class under controllers folder without use
namespace
, so I use
__autoload
function like:

index.php



<?php

include 'vendor/autoload.php';

function __autoload($class_name) {
include 'controllers/' . $class_name . '.php';
}


new Test // Fatal error: Class 'test'


If I remove
include 'vendor/autoload.php';
it will work, so I think the code is correct, I know I can use
classmap
in
composer.json
, but it need to
dump-autoload
everytime I add a new class, how to deal with the conflict?

Answer

You do not have to use your own implementation of autoloading. You could use composer autoloading for all classes.

{
    "autoload": {
        "psr-0": { "": "src/" }
    }
}

https://getcomposer.org/doc/04-schema.md#psr-0

Or, you could create class map

https://getcomposer.org/doc/04-schema.md#classmap

p.s. indeed, you could use empty namespace with psr-4.

Comments