Making the model require database connection only wen needed or requested

This commit is contained in:
José Lorenzo Rodríguez Urdaneta 2010-07-15 21:16:52 -04:30
parent 67612872da
commit a13be623b5
2 changed files with 18 additions and 7 deletions

View file

@ -462,16 +462,16 @@ class Model extends Object {
$this->Behaviors = new BehaviorCollection();
if ($this->useTable !== false) {
$this->setDataSource($ds);
if ($this->useTable === null) {
$this->useTable = Inflector::tableize($this->name);
}
$this->setSource($this->useTable);
if ($this->displayField == null) {
$this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
}
$this->table = $this->useTable;
$this->tableToModel[$this->table] = $this->alias;
} elseif ($this->table === false) {
$this->table = Inflector::tableize($this->name);
}
@ -785,7 +785,7 @@ class Model extends Object {
*/
public function setSource($tableName) {
$this->setDataSource($this->useDbConfig);
$db = $this->getDataSource();
$db = ConnectionManager::getDataSource($this->useDbConfig);
$db->cacheSources = ($this->cacheSources && $db->cacheSources);
if ($db->isInterfaceSupported('listSources')) {
@ -800,7 +800,6 @@ class Model extends Object {
}
$this->table = $this->useTable = $tableName;
$this->tableToModel[$this->table] = $this->alias;
$this->schema();
}
/**
@ -2790,7 +2789,7 @@ class Model extends Object {
if ($dataSource != null) {
$this->useDbConfig = $dataSource;
}
$db = $this->getDataSource();
$db = ConnectionManager::getDataSource($this->useDbConfig);
if (!empty($oldConfig) && isset($db->config['prefix'])) {
$oldDb =& ConnectionManager::getDataSource($oldConfig);
@ -2813,6 +2812,11 @@ class Model extends Object {
* @return object A DataSource object
*/
public function &getDataSource() {
static $configured = false;
if (!$configured && $this->useTable !== false) {
$configured = true;
$this->setSource($this->useTable);
}
return ConnectionManager::getDataSource($this->useDbConfig);
}

View file

@ -2961,10 +2961,17 @@ class ModelWriteTest extends BaseModelTest {
$db = ConnectionManager::create('mock_transaction', array(
'datasource' => 'MockTransactionDbo',
));
$db->expects($this->at(2))
->method('isInterfaceSupported')
->with('describe')
->will($this->returnValue(true));
$db->expects($this->once())
->method('describe')
->will($this->returnValue(array()));
$db->expects($this->once())->method('rollback');
$Post = new Post();
$Post->useDbConfig = 'mock_transaction';
$Post = new Post('mock_transaction');
$Post->validate = array(
'title' => array('rule' => array('notEmpty'))