Question

I have a table named 'table' that stores the details of other tables in database. I am now creating a functionality such that whenever the table name gets inserted in this table, the same table is created. For ex, if I insert a table named 'wf_128fe' then the same table is created with some dynamic fields. Now, since we are creating new tables on the fly, we do not create MVC for each table. In this case, how can we retrieve/store values in these tables.

<?php
$table='wf_128fe';
$table_details=$this->$table->find('all');
?>

This didn't worked as new table does not have any Model. In such case, how can I retrieve details/store data in that new table.

Was it helpful?

Solution

First of all you might want to rethink what you are doing there, dynamically creating tables should only be necessary in very rare edge cases, so there are most probably better ways to achieve whatever you are trying to achieve with this dynamic table stuff, while also sticking to CakePHP standards.

That being said, using a generic model for this purpose should work, instantiate it using ClassRegistry::init() and pass the appropriate table name. That would even work with only an AppModel class being present, which is being used as a fallback by ClassRegistry::init().

$Model = ClassRegistry::init(array('class' => 'Wf128fe', 'table' => 'wf_128fe'));
$details = $Model->find('all');

This would create an instance of AppModel, with Wf128fe as Model::$name and Model::$alias, and wf_128fe set for Model::$table and Model::$useTable.

In case you need specific methods, properties, etc, the mentioned generic model might be the way to go:

class DynamicTable extends AppModel
{
    public function someMethodDoingSomethingSpecialSpecificToDynamicTables()
    {
    }
}
$Model = ClassRegistry::init(array('class' => 'DynamicTable', 'table' => 'wf_128fe'));
$details = $Model->find('all');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top