Custom class in package not found

Hello everyone,

I’m trying without success to make a package with custom classes.
Here is my package structure

I added this code in my package controller as suggested by the online documentation

protected $pkgAutoloaderRegistries = array(
    'src/junglebob/myclasses' => '\Junglebob\Myclasses');

That’s the code of my “test_class.php” file.
I found a discussion mentioning that the package path is not needed. Is that correct ?
Is the namespace correct in this specific case ?

namespace Junglebob\Myclasses;
defined('C5_EXECUTE') or die(_("Access Denied."));

class TestClass
    public function testFunction()
        $test='This is a test !';
        return $test;

Finally here’s the code in my page template (i.e. full.php) where I want to instantiate my custom class. I tried to specify almost everything after the ‘use’ keyword and always get the “Class ‘TestClass’ not found
What should be specified after the ‘use’ keyword in this specific case ?
Is it the correct place to instantiate the class ?
Otherwise what should be done to make this class available to my pages ?

		use  Junglebob\Myclasses;
		$test = new TestClass();
		echo $return;

Thanks for your help !

use Junglebob\Myclasses\TestClass;

and the file name

[edit] In fact the directory path would be

And also use that in the autoload array.

The general rule (except where historically different for things like blocks and single pages) is that the path, namespace and class names should be CapitalCase and match exactly.

1 Like

As an aside, the exec or die can be simpler

defined('C5_EXECUTE') or die('Access Denied.');

Thank you for your help.
I actually just had to change the filename as you suggested. I guess the convention is to name the files containing the classes following the “Upper Camel Case” rule.
Regarding the “autoload array”, I did not have to change anything.

I now have another question : what is the best practice when you want to use a function in a class on a page? Is it really desirable to instantiate it directly within the page (it’s usually done in a controller isn’t it ?) ? Should I rather extend an existing class and which one in this case ? Or should I make this class global so I can “call” it from anywhere, how do I do that ? This is really not very clear to me :thinking:

You 're totally right.
I didn’t check this portion of code in fact. It’s the result of a bad copy/paste from another discussion.

There is no black and white rule against instantiating a class to call a method in the view. Its very subjective. As a general guide

  • classes that help provide output (or input, such as forms)
  • Formatting
  • All sorts of utilities

Provisioning data to the view
Complicated logic that decides what is going to be shown in the view
Telling the core to provide js/css assets to the view

But there will always be exceptions, grey areas.

1 Like

Allright, thanks for your answer