We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

[Universal Class Loader] Can't load class

Hello folks,

I have a class called CurrencyConversor.php located at /app/library/classes/, and i'm trying to use Universal Class Loader functionality from Phalcon to use it into my controllers. Here is what I'm trying:

index.php

 //Register an autoloader
    $loader = new \Phalcon\Loader();

    //...other stuff...

    $loader->registerClasses([
        'CurrencyConversor' => 'library/classes/CurrencyConversor.php'
    ]);

    $loader->register();

//...

SomeController.php

public function doAction()
{
    $cc = new CurrencyConversor();
}

And this is what I get when i load the controller:

Fatal error:  Class 'CurrencyConversor' not found in C:\the\path\to\phalcon_app\app\controllers\SomeController.php on line 63

What am I doing wrong? Isn't it the right way to implement a Universal Class?

try escpecfying an absolute route to the loader

edited Mar '14

Just checking, but did you make sure to include a use statement?

use CurrencyConversor;

Also, is the class namespaced as it should be? If so, you will need to add that to the registerClasses() call and use statement.

@moderndeveloperllc I've tried adding this on the top of the controller but didn't work. The problem continues. Also, is the use statement really needed? I thought that you needed to do was add the registerClasses to index.php and then call it in your controller (as seen in docs examples).

I didn't found anything about the use statement (for Phalcon).

You may want to try this: https://docs.phalcon.io/en/latest/reference/loader.html#autoloading-events to see what paths Phalcon actually tries.



5.3k
Accepted
answer
edited Mar '14

By using

$cc = new CurrencyConversor();

You are telling the file that you want the class, but you are not telling it what namespace it can go find the class in. My previous comment was a bit wrong in that it did not include the full namespace path. One would think that registerClasses would take care of this, but I guess not.

So, all the steps that are needed:

Your CurrencyConversor class should be namespaced, even if it's just one level: (in library/classes/CurrencyConversor.php)

namespace Kazzkiq;

You can then use registerNamespaces()

$loader->registerNamespaces(array(
    //Other namespaces
    'Kazzkiq' =>'library/classes'
));

Add the use statement at the top of your controller class so it knows where to find the library class:

use Kazzkiq\CurrencyConversor;

//stuff
public function doAction()
{
    $cc = new CurrencyConversor();
}

Or you can reference the full namespaced class without the use statement:

public function doAction()
{
    $cc = new Kazzkiq\CurrencyConversor();
}

YMMV, - Mark