0
votes

I'm new to composer to manage the loading of my custom classes. I'm trying to add some custom classes to the autoload but without success, I will get always a Class not found... error.

How I will setup correctly composer, where I should put the composer.json file with the psr-4 info about my custom class/classes?

Can anyone help me understand how it will work in this case? Here is my class code snippet, I'm using some composer packages so I need to autoload them. This file is placed in it's own directory. th structure looks like this: project_root\assets\library\MyClassFolder

<?php
namespace MyNamespace;

require_once __DIR__.'/vendor/autoload.php';

use \Foo\Bar;

class MyClass {
 ...
}

?>

This is the code where the class need to be loaded. This file is located inside my project root folder and it's causing the error:

<?php

require_once __DIR__.'/vendor/autoload.php';

use \MyNamespace\MyClass;

if( isset($_POST['do_action']) ){
MyClass::init();
}
?>

This is the composer.json file that is in the project root:

{
    "require": {
        "gabordemooij/redbean": "^5.3"
    },
    "autoload": {
      "psr-4": {
        "MyNamespace\\": "assets/library/"
      }
    }
}

1
Can you share the full and exact error message, and the exact file names? If your namespace is called MyNamespace, then your folder should not be named MyClassFolderNico Haase
@NicoHaase The folder name is the same of the namespace, I've used MyClass folder to be more clear in the question. The error i get is /controller.php - Uncaught Error: Class 'MyNamespace\MyClass' not foundOshione

1 Answers

0
votes

I've found a fix, I was made a mistake inside the composer.json file. I was not pointing the namespace to the classes directory. This is why I've got a Class not found... error.

the composer file now look like this:

{
    "require": {
        "gabordemooij/redbean": "^5.3"
    },
    "autoload": {
      "psr-4": {
        "MyNamespace\\": "assets/library/MyClassFolder/"
      }
    }
}

I also needed to change the require_once inside the custom classes files to point to the vendor path where reside the autoload file.

Instead of require_once __DIR__.'/vendor/autoload.php'

Now I've

require_once dirname(__DIR__, 3).'/vendor/autoload.php' This because the