Last active
January 13, 2018 06:03
-
-
Save muthu32/31aeb9befa5ced7837f874ff1f2d6ea8 to your computer and use it in GitHub Desktop.
Singleton design pattern and pool design pattern to increase efficiency of code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class produkt_pool | |
{ | |
protected static $instance = array(); | |
public static function get_instance($pid) | |
{ | |
if(!isset(self::$instance[$pid])) | |
{ | |
self::$instance[$pid] = new produkt($pid); | |
} | |
return self::$instance[$pid]; | |
} | |
//another type of instance if instance was not array | |
public static function &Instance() | |
{ | |
static $instance; | |
if (!isset($instance)) | |
{ | |
$c = __CLASS__; | |
$instance = new $c; | |
} | |
return $instance; | |
} | |
} | |
class produkt | |
{ | |
public $data; | |
public function __construct($pid) | |
{ | |
echo "<br />PID ",$pid," is initiated<br />"; | |
switch($pid) | |
{ | |
case '1': $this->data = array("test"=>3,"Value"=>4); | |
break; | |
case '2': $this->data = array("test"=>20,"Value"=>50); | |
break; | |
} | |
return $this; | |
} | |
public function __call($method, $arguments) | |
{ | |
if(true === array_key_exists($method, $this->data)) | |
{ | |
if(is_array($this->data[$method]) && count($arguments) > 0) | |
{ | |
if(true === array_key_exists($arguments[0], $this->data[$method])) | |
{ | |
return new self($this->data[$method][$arguments[0]]); | |
} | |
} | |
return $this->data[$method]; | |
} | |
} | |
} | |
/* | |
$data = new produkt(1); | |
echo $data->value(); | |
*/ | |
echo "INIT PID 1<br />"; | |
$data1 = produkt_pool::get_instance(1); | |
echo "<br />"; | |
echo "PID 1 TEST",$data1->test(); | |
echo "<br />INIT PID 2<br />"; | |
$data1 = produkt_pool::get_instance(2); | |
echo "<br />"; | |
echo "PID 2 TEST",$data1->test(); | |
$data1 = produkt_pool::get_instance(1); | |
echo "<br />"; | |
echo "PID 1 VALUE",$data1->Value(); | |
$data1 = produkt_pool::get_instance(2); | |
echo "<br />"; | |
echo "PID 2 VALUE",$data1->Value(); | |
echo "<br />"; | |
echo "<br />"; | |
echo "<br />"; | |
$data = produkt_pool::get_instance(1); | |
echo $data->test(),"<br />"; | |
echo $data->Value(),"<br />"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment