we use dynamic table on our application, we do it like this:
<?php
namespace App\Models;
class Test extends \Phalcon\Mvc\Model implements \Phalcon\Mvc\ModelInterface
{
private $_type = null;
/**
* Initialize method for model.
*/
public function initialize()
{
}
public function onConstruct($param = [])
{
if (isset($param['type'])) {
$this->_type = $param['type'];
}
}
/**
* Returns table name mapped in the model.
*
* @return string
*/
public function getSource()
{
switch ($this->_type) {
case 1:
$source = 'test01';
break;
case 2:
$source = 'test02';
break;
default:
$source = 'test';
break;
}
return $source;
}
// a test function
public function getTestData()
{
$results = $this->find();
return $results;
}
}
then i call getTestData like this:
$testModel = new Test(['type' => 2]);
$results = $testModel->getTestData();
it will call onConstruct method twice, no parameter for onConstruct at the second time, ,it will create new instance for Model test when call find or findFirst to get data.
how can we use the first initialized model $testModel?
log created by $testModel = new Test(['type' => 2]);
#0 App\Models\Test->onConstruct(Array ([type] => 1))
#1 Phalcon\Mvc\Model->__construct(Array ([type] => 1)) called at [D:\01 develop\www\application\models\BaseModel.php:49]
#2 App\Models\BaseModel::getModel(test, Array ([type] => 1)) called at [D:\01 develop\www\application\controllers\Test2Controller.php:47]
#3 App\Controllers\Test2Controller->cAction()
#4 Phalcon\Dispatcher->callActionMethod(App\Controllers\Test2Controller Object (...))
#5 Phalcon\Dispatcher->_dispatch()
#6 Phalcon\Dispatcher->dispatch()
#7 Phalcon\Mvc\Application->handle() called at [D:\01 develop\www\public\index.php:48]
----------------------------------------------------------------------------------------------------------------------------------------
log created by $results = $testModel->getTestData();
#0 App\Models\Test->onConstruct()
#1 Phalcon\Mvc\Model->__construct(, Phalcon\Di\FactoryDefault Object (...))
#2 Phalcon\Mvc\Model\Manager->load(App\Models\Test, 1)
#3 Phalcon\Mvc\Model\Query->_prepareSelect()
#4 Phalcon\Mvc\Model\Query->parse()
#5 Phalcon\Mvc\Model\Query->execute()
#6 Phalcon\Mvc\Model::find() called at [D:\01 develop\www\application\models\Test.php:38]
#7 App\Models\Test->getTestData() called at [D:\01 develop\www\application\controllers\Test2Controller.php:48]
#8 App\Controllers\Test2Controller->cAction()
#9 Phalcon\Dispatcher->callActionMethod(App\Controllers\Test2Controller Object (...))
#10 Phalcon\Dispatcher->_dispatch()
#11 Phalcon\Dispatcher->dispatch()
#12 Phalcon\Mvc\Application->handle() called at [D:\01 develop\www\public\index.php:48]
thanks in advance.