Browse Source

Merge pull request #8241 from CakeDC/3.2-table-registry-connection-name-7644

Allow to use the connection name with the option "connectionName" in TableLocator::get()
Mark Story 10 years ago
parent
commit
d475a242e7

+ 7 - 1
src/ORM/Locator/TableLocator.php

@@ -116,6 +116,8 @@ class TableLocator implements LocatorInterface
      * If no `table` option is passed, the table name will be the underscored version
      * of the provided $alias.
      *
+     * If no `connection` option is passed and passed `connectionName` string then it's used as original name to instantiate connection.
+     *
      * If no `connection` option is passed the table's defaultConnectionName() method
      * will be called to get the default connection name to use.
      *
@@ -161,7 +163,11 @@ class TableLocator implements LocatorInterface
         }
 
         if (empty($options['connection'])) {
-            $connectionName = $options['className']::defaultConnectionName();
+            if (!empty($options['connectionName'])) {
+                $connectionName = $options['connectionName'];
+            } else {
+                $connectionName = $options['className']::defaultConnectionName();
+            }
             $options['connection'] = ConnectionManager::get($connectionName);
         }
 

+ 2 - 0
src/ORM/TableRegistry.php

@@ -100,6 +100,8 @@ class TableRegistry
     /**
      * Get a table instance from the registry.
      *
+     * See options specification in {@link TableLocator::get()}.
+     *
      * @param string $alias The alias name you want to get.
      * @param array $options The options you want to build the table with.
      * @return \Cake\ORM\Table

+ 15 - 0
tests/TestCase/ORM/Locator/TableLocatorTest.php

@@ -222,6 +222,21 @@ class TableLocatorTest extends TestCase
     }
 
     /**
+     * Test that get() uses config data set with config()
+     *
+     * @return void
+     */
+    public function testGetWithConnectionName()
+    {
+        ConnectionManager::alias('test', 'testing');
+        $result = $this->_locator->get('Articles', [
+            'connectionName' => 'testing'
+        ]);
+        $this->assertEquals('articles', $result->table());
+        $this->assertEquals('test', $result->connection()->configName());
+    }
+
+    /**
      * Test that get() uses config data `className` set with config()
      *
      * @return void