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

Best ways to reuse same instance of model in Phalcon

I have to call some methods of my model several times in many controller's methods. At this moment, I am doing something like this:

$songs = (new Media)->getSongs($arguments);

I wonder is it a good idea to reuse the Media instance instead of create new in each method? (those methods work together in a single request)

I see some code base is using "Lazy Load Pattern" here:

public static function model()
{
    static $instance = null;
    if (null === $instance) {
        $instance = new static();
    }
    return $instance;
}

So we can do this everywhere:

$songs = Media::model()->getSongs($arguments);

Is it a good idea to use this pattern here? Or is there any better ways to handle this case?

Thank you.

edited Oct '14

You can add this static method to your model class

public static function getSongs($arguments)
{
    // process......
    return $songs;
}

and use it like:

$songs = Media::getSongs($arguments);
edited Nov '14

I'm using modelsManager to get data from DB, below code contains in the getSongs():

$manager = $this->getModelsManager();
$builder = $manager->createBuilder();

So I cannot change the method to static. Is there any ways to work around this case?



24.1k
Accepted
answer
edited Dec '14

Hi

there is different ways to do :

use

$di = DI::getDefault();
$manager = $di->get('modelsManager');

in a static class as proposed by @a6oozar

or use the already static functions in your model : find , findFirst and query which will provide quite everything you want (which i think is the best way.

so your getSongs method will look as something like

public static function getSongs($arguments)
{
  return self::query()
      ->where('blabla')
      ->execute();
}

@ogarbe: find() and findFirst() don't support join so I cannot use them, then I accidentally skipped query() part in the doc. Thanks for your answer, now I could refactor all of the code in models without using Lazy Load.