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

set name table dynamic + find

Hi, I have tables in my database that is dynamic and i want create a generic model for represent this tables! The problem is, how i can pass the name of table into the find method static?

Thanks so much!

edited Mar '16

By using:

$modelsManager = $di->get('modelsManager')
$modelsManager->setModelSource('namespace','table name') // to set table
$modelsManager->setModelSchema('namespace','database/schema name') // to set database/schema

In some part of code if you want to change it.

But remember that will change whole model to this schema/source.

Or in model defitnion:

public function getSchema()
{
    return "schema/database name"; // you can for example create config file and get it from config
}

public function getSource()
{
    return "table name"; // you can for example create config file and get it from config
}

You can always extend find method like this:

public static function find($parameters = null)
{
    $modelsManager = Di::getDefault()->get('modelsManager');
    if isset($parameters,$parameters['schema']){
        $modelsManager->setModelSchema(get_called_class(),$parameters['schema']);
    }
    if isset($parameters,$parameters['source']){
        $modelsManager->setModelSource(get_called_class(),$parameters['source']);
    }
    return parent::find($parameters);
}

But in all those solutions there are ONE basic problem - PHQL cache, in Phalcon 1 you could __destruct modelsManager which will clear phql cache, but in 2 this method is missing.

But maybe you are not going to change schema/source when application is running, only setting it on bootstrap, then i recommend second option and just config file.