Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 676
Chan Avatar asked Jul 31 '26 09:07

Chan


1 Answers

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.

like image 93
sectus Avatar answered Aug 01 '26 22:08

sectus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!