title: How to use multiple databases dynamically for one model in CakePHP
body: <p>Ok, my first question was modified so many times that I chose to delete it and reformulate my question. I've made a small test-case project with different model-names to find a proper solution for my problem.</p>
  
  <p><strong>Warning</strong>: Don't mix the <strong>databases</strong> up with <strong>tables</strong></p>
  
  <p><strong>Motivation</strong>: I separated the user-data into multiple <strong>databases</strong> for legal &amp; performance issues.</p>
  
  <p>Currently I'm working on a <strong>CakePHP</strong> project that has multiple <code>User</code>'s and each <code>User</code> has it's own <strong>database</strong> with multiple <strong>tables</strong> (<code>cars</code> is one of the <strong>tables</strong>). Now, I need to explain something first:</p>
  
  <p>Every <code>User</code> has his own <strong>database</strong> (not a table, a <strong>database</strong>), so the database names are as follows.</p>
  
  <ul>
  <li>[DATABASE] <code>app</code> (This is the app's main database)
  
  <ul>
  <li>[TABLE] <code>users</code> </li>
  <li>[TABLE] <code>permissions</code> (<em>Not relevant for this question</em>)</li>
  </ul></li>
  <li>[DATABASE] <code>app_user1</code> (<code>User.id</code> 1 owns this entire <strong>database</strong>)
  
  <ul>
  <li>[TABLE] <code>cars</code> (a <strong>table</strong> entirely owned by <code>User.id</code> 1)</li>
  </ul></li>
  <li>[DATABASE] <code>app_user2</code> (<code>User.id</code> 2 owns this entire <strong>database</strong>)
  
  <ul>
  <li>[TABLE] <code>cars</code> (a <strong>table</strong> entirely owned by <code>User.id</code> 2)</li>
  </ul></li>
  <li>etc...</li>
  </ul>
  
  <p>I made a small drawing which might clarify the <strong>database</strong> / <strong>table</strong> -definitions and their relations to the models:</p>
  
  <p><img src="https://i.stack.imgur.com/zU6Db.png" alt="How to use multiple databases dynamically for one model in CakePHP"></p>
  
  <p><strong>The problem!!!</strong></p>
  
  <p>I don't know which <strong>database</strong> to connect to until the <code>User</code> logs in. <code>User</code>'s and their <strong>databases</strong> are created dynamically, so I cant use <code>app/Config/database.php</code>.</p>
  
  <p>So I'm currently writing an extension on the <code>Model</code> and <code>ConnectionManager</code> classes to bypass CakePHP's basic database behaviors. So the <code>Car</code> model knows which <strong>database</strong> to use. But I just have a feeling this could be done easier!</p>
  
  <p>So I guess it all boils down to one question:</p>
  
  <p><strong>Is there an easier way of doing this?!</strong></p>
  
  <p>Thanks to anyone who will take the time and effort of reading and understanding my problem!</p>