Introduce caching factory for objects
authorJoey Schulze <joey@infodrom.org>
Sun, 9 Jul 2017 10:14:54 +0000 (12:14 +0200)
committerJoey Schulze <joey@infodrom.org>
Sun, 9 Jul 2017 12:02:45 +0000 (14:02 +0200)
class/factory.class.php [new file with mode: 0644]

diff --git a/class/factory.class.php b/class/factory.class.php
new file mode 100644 (file)
index 0000000..b2330e5
--- /dev/null
@@ -0,0 +1,36 @@
+<?php
+
+final class Factory {
+  private static $objectStore = array();
+
+  public static function get()
+  {
+    if (!func_num_args())
+      throw new Exception('Factory::get called without class name');
+
+    $args = func_get_args();
+    $class = array_shift($args);
+
+    $obj = self::getInstance($class, $args);
+
+    if ($obj === false) {
+      $reflection = new ReflectionClass($class);
+      $obj = $reflection->newInstanceArgs($args);
+      self::$objectStore[$class][] = array('args' => $args, 'object' => $obj);
+    }
+
+    return $obj;
+  }
+
+  private static function getInstance($class, $args)
+  {
+    if (!array_key_exists($class, self::$objectStore)) return false;
+
+    foreach (self::$objectStore[$class] as $item) {
+      if ($item['args'] == $args)
+       return $item['object'];
+    }
+
+    return false;
+  }
+}