title: Opening database connection in controller (connection pattern)
body: <p>I've got to implement a database connection pattern. I created two classes:</p>
  
  <ul>
  <li><strong>ConnectionFactory</strong></li>
  <li><strong>MySQLService</strong></li>
  </ul>
  
  <p><strong>ConnectionFactory:</strong></p>
  
  <pre><code>&lt;?php
  
    class ConnectionFactory {
      protected static $connection;
  
      public function getConnection() {
          if (!self::$connection) {
              self::$connection = new PDO('mysql:host=localhost;dbname=sapienter', "root", "admin");
          }
          return self::$connection;
      }
    }
  
  ?&gt;
  </code></pre>
  
  <p><strong>MySQLService:</strong></p>
  
  <pre><code>&lt;?php
  
    class MySQLService {
      protected $connectionFactory;
  
      public function __construct(ConnectionFactory $factory) {
        $this-&gt;connectionFactory = $factory;
      }
  
      public function listItemsForSharerSQL() {
        $conn = $this-&gt;connectionFactory-&gt;getConnection();
        $items = ...
        return $items;
      }
    }
  
  ?&gt;
  </code></pre>
  
  <p>I call these methods in my controller <strong>ItemController</strong>:</p>
  
  <pre><code>&lt;?php
  
  require_once ROOT_DIR . "/models/Item.php";
  require_once ROOT_DIR . "/ConnectionFactory.php";
  require_once ROOT_DIR . "/MySQLService.php";
  
  class ItemController {
  
      private $data;
  
      public function listItemsForSharer() {
          $connFactory = new ConnectionFactory();
          $service = new MySQLService($connFactory);
          $items = $service-&gt;listItemsForSharerSQL();
  
          $this-&gt;data = ['items' =&gt; $items];
          return 'itemslistforsharer-view';
      }
  }
  
  ?&gt;
  </code></pre>
  
  <p>I don't like the fact that I've got to instantiate a new ConnectionFactory in my Controller. Is it a mistake? Should I change my code design?</p>