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

phalcon load classes from directory

Hi everyone! I have a problem with loading "Model" classes from directory in phalcon framework 2.0.

I can't use namespaces now, because project is migrating step by step from ZF1, and Model classes has many dependencies with themselves. If I register namespaces for every directory - loader works great, but I need to do that without namespaces.

So I do that:

$loader = new \Phalcon\Loader();
$loader->registerDirs(
    [
        /** Phalcon controllers */
        $configPhalcon->application->controllersDir, /** Phalcon controllers */
        /** Models */
        $configPhalcon->application->servicesDir,
        ...
        ...
    ],
    true
)->register();

Class name are Service_Name(), where Service - directory. File name are Name.php, so I need to register class prefixes for directories:

$loader->registerPrefixes(
    [
        'Service_' => $configPhalcon->application->servicesDir,
        ...
        ...
    ],
    true
)->register();

Now, I want to get my service class:

$serv  = new Service_Name();

and get Fatal error: Class 'Service_Name' not found. Help me please what I do wrong?

If I register namespace:

$loader->registerNamespaces( [ 'Service' => $configPhalcon->application->servicesDir, ], true )->register();

I can get my class like that:

$serv = new Service\Name();

but I want to get it by class name.



1.8k
Accepted
answer

I found the solution! I had phalcon 1.3 and everything works fine, then I updated phalcon to 2.0 version, and don't test autoload.

The difference is in Prefix for directory classes

in 1.3 version I use 'Service_'

in 2.0 works fine just 'Service'

So, the solution is

$loader->registerPrefixes(
[
    'Service' => $configPhalcon->application->servicesDir,
    ...
    ...
],
true
)->register();