Browse Source

Lazy-loading the $tablePrefix property in models, Fixes #2277

Jose Lorenzo Rodriguez 14 years ago
parent
commit
73aeb6ba62
2 changed files with 30 additions and 0 deletions
  1. 12 0
      lib/Cake/Model/Model.php
  2. 18 0
      lib/Cake/Test/Case/Model/ModelIntegrationTest.php

+ 12 - 0
lib/Cake/Model/Model.php

@@ -701,6 +701,11 @@ class Model extends Object {
 		} elseif ($this->table === false) {
 			$this->table = Inflector::tableize($this->name);
 		}
+
+		if ($this->tablePrefix === null) {
+			unset($this->tablePrefix);
+		}
+
 		$this->_createLinks();
 		$this->Behaviors->init($this->alias, $this->actsAs);
 	}
@@ -800,6 +805,13 @@ class Model extends Object {
 		if ($name === 'displayField') {
 			return $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
 		}
+		if ($name === 'tablePrefix') {
+			$this->setDataSource();
+			if (property_exists($this, 'tablePrefix')) {
+				return $this->tablePrefix;
+			}
+			return $this->tablePrefix = null;
+		}
 		if (isset($this->{$name})) {
 			return $this->{$name};
 		}

+ 18 - 0
lib/Cake/Test/Case/Model/ModelIntegrationTest.php

@@ -2049,6 +2049,7 @@ class ModelIntegrationTest extends BaseModelTest {
 		$result = $TestModel->escapeField('DomainHandle', 'Domain');
 		$expected = $db->name('Domain.DomainHandle');
 		$this->assertEquals($expected, $result);
+		ConnectionManager::drop('mock');
 	}
 
 /**
@@ -2073,4 +2074,21 @@ class ModelIntegrationTest extends BaseModelTest {
 		$this->assertTrue($Article->hasMethod('pass'));
 		$this->assertFalse($Article->hasMethod('fail'));
 	}
+
+/**
+ * Tests that tablePrefix is taken from the datasource if none is defined in the model
+ *
+ * @return void
+ * @see http://cakephp.lighthouseapp.com/projects/42648/tickets/2277-caketestmodels-in-test-cases-do-not-set-model-tableprefix
+ */
+	public function testModelPrefixFromDatasource() {
+		ConnectionManager::create('mock', array(
+			'datasource' => 'DboMock',
+			'prefix' => 'custom_prefix_'
+		));
+		$Article = new Article(false, null, 'mock');
+		$this->assertEquals('custom_prefix_', $Article->tablePrefix);
+		ConnectionManager::drop('mock');
+	}
+
 }