<?php

namespace Hwapx\Core\Library\Db;

use DB\Cortex as F3Cortex;

class Cortex extends F3Cortex {
  protected static $_extendHooks = array();
  protected static $_instances = array();

  public function __construct($db = NULL, $table = NULL, $fluid = NULL, $ttl = 0) {
    parent::__construct($db, $table, $fluid, $ttl);

    self::$_instances[] = $this;
    foreach (self::_extendHooks as $extendHook)
      $this->extend($extendHook);
  }

  public function extend($misc) {
    $data = new stdObject();

    if(is_callable($misc)) {
      $misc($data);
    } else {
      $data = (object)$misc;
    }

    foreach ($data as $key => $value)
      $this->{$key} = $value;
  }

  public static function extend($misc) {
    self::_extendHooks[] = $misc;

    foreach (self::$_instances as $instance)
      foreach (self::_extendHooks as $extendHook)
        $instance->extend($extendHook);
  }

  public function __destruct() {
    for ($i=0; $i < count(self::$_instances); $i++)
      if($i === $this)
        unset(self::$_instances[$i]);
  }
}