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

Using modelsManager in model

Hi,

I'm trying modelsManager in model and getting following error:

( ! ) Fatal error: Cannot redeclare class Apphalcon\Models\Portfolios in D:\wamp\www\webrati\app\models\Portfolios.php on line 178

Here my custom method in Portfolios model.

 public static function getRecents()
 {
    $modelsManager = Di::getDefault()->getModelsManager();

    $phql = "   SELECT      p.*
                FROM        portfolios as p
                WHERE       u.is_active = :active:                  
                ORDER BY    p.created DESC";

    $query = $modelsManager->createQuery($phql);
    $results = $query->execute(
        [
            'active' => '1'
        ]
    );

    return $results;    
 }

What is missing? Thanks

Paste you loader.php

Are you using namespaces?



58.1k

Yes, i'm using namespaces:

namespace Apphalcon\Models;

Here my loader:

<?php

use Phalcon\Loader;

$loader = new Loader();

/**
 * We're a registering a set of directories taken from the configuration file
 */
$loader->registerDirs(
    array(
        $config->application->eventsDir,
        $config->application->modelsDir,
        $config->application->libraryDir
    )
);

$loader->registerNamespaces([
    'Apphalcon\Events'          => $config->application->eventsDir,
    'Apphalcon\Tasks'           => $config->application->tasksDir,
    'Apphalcon\Models'          => $config->application->modelsDir,
    'Apphalcon\Controllers'     => $config->application->controllersDir,
    'Apphalcon\Forms'           => $config->application->formsDir,
    'Apphalcon'                 => $config->application->libraryDir
]);

$loader->register();

// Use composer autoloader to load vendor classes
require_once __DIR__ . '/../../vendor/autoload.php';

It seems like you're loding the model file a second time somehow, I don't think it has to do anything with the DI...



145.0k
Accepted
answer

As you see you registering models dir, events dir and library dir both times. Just remove this:

$loader->registerDirs(
    array(
        $config->application->eventsDir,
        $config->application->modelsDir,
        $config->application->libraryDir
    )
);

Call Portofolios:

$foo = new Apphalcon\Models\Portfolios();

Error is because: It means you've already created a class.

For instance:

class Foo {}

// some code here

class Foo {}

That second Foo would throw the error.



58.1k

As you see you registering models dir, events dir and library dir both times. Just remove this:

$loader->registerDirs(
   array(
       $config->application->eventsDir,
       $config->application->modelsDir,
       $config->application->libraryDir
   )
);

When these line removed, it works. But it was working before using modelsManager. Is this normal?

Yes it's normal, thanks to lazy-loading