title: Design Patterns: How to create database object/connection only when needed?
body: <p>I've a simple application, say it has some classes and an "extra" one that handles database requests. Currently i'm creating the database object everytime the app is used, but in some cases there's no need for a database connection. I'm doing it like this (PHP btw):</p>
  
  <pre><code>$db = new Database();    
  $foo = new Foo($db); // passing the db
  </code></pre>
  
  <p>But sometimes the <code>$foo</code> object does not need db access, as only methods without database actions are called. So my question is: What's the professional way to handle situations like this / how to create the db connection/object only when needed ?</p>
  
  <p><em>My goal is to avoid unnecessary database connections.</em></p>