Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.



855
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();