How can I do a better implementation for a no-db Cake APP using the DBs found by the database config?

I'm creating a simple interactive courseware for MySQL using CakePHP w/ jQuery.

The APP doesn't need it's own database, but rathar use what's provided on config/database.php. Providing a root user, all databases/tables can be used. Specifying users other than root shows their privileged databases/tables accordingly.

By creating the models Database** and **Tables**, I've managed to show all tables and databases by overriding the **find() operation of each model. But this is accomplished by hard-coding arrays in the model that can be used by the controller as well as the views, following cake conventions.

For the databases, I execute a $this->query("SHOW DATABASES") and construct the data array like so:


function find($type, $options = array(), $order = null, $recursive = null) {
$items = $this->query('SHOW DATABASES');
$databases = Set::extract('/SCHEMATA/Database', $items);
$counter_db = 1;
foreach($databases as $database) {
	$current = array (
			'Database'=>array (
					'id' => $counter_db++,
					'name' => $database
			),
	);
	$this->query('USE '.$database);

	// Show tables in the selected db
	$_tables = $this->query('SHOW TABLES');
	$tables = Set::extract('/TABLE_NAMES/Tables_in_'.$database, $_tables);
	$counter_table = 1;
	foreach($tables as $table) {
		$current['Table'][] = array(
				'id' => $counter_table++,
				'name' => $table,
				'database_id' => $counter_db
		);
	} // end foreach
	$this->databases[] = $current;
} // end foreach
switch ($type) {
	case 'all':
		return $this->databases;
		break;
	case 'count';
		return count($this->databases);
		break;
	case 'list':
		return Set::combine($this->databases, '{n}.'.$this->alias.'.id', array(
				'%s'
				, '{n}.'.$this->alias.'.'.'name'
			)
		);
		break;
         default:
                return parent::find($type, $options, $order, $recursive);
                break;
} // end switch
}

Is this process on the right track or something better could be done?

Asked by sonnygauran, on 9/2/10

1 Answer

The idea is there. but i would say this should be either a datasource or a behavior.

here is an example of something done in a behavior

http://github.com/infinitas/infinitas/blob/master/extensions/libs/models/behaviors/feedable.php

and this is how its used

http://github.com/infinitas/infinitas/blob/master/infinitas/blog/controllers/posts_controller.php#L168

this is much better as a lot of people will have already overloaded the find method like you have and to then try and implement your code is a problem, and if its a behavior its simple to implement.

Answered by dogmatic69on 9/2/10

<< previous next >>

Your Answer

You can use Creole Wiki Syntax to format your text.

Tagged with

Rating

0

Viewed

233 times

Last Activity

on 9/2/10