Skip to content

Instantly share code, notes, and snippets.

@diloabininyeri
Last active November 5, 2018 12:02
Show Gist options
  • Save diloabininyeri/e21279288efd7b8a73d0cbed48eebb79 to your computer and use it in GitHub Desktop.
Save diloabininyeri/e21279288efd7b8a73d0cbed48eebb79 to your computer and use it in GitHub Desktop.
<?php
/**
* Class Pool
* @author dılo sürücü <berxudar@gmail.com>
* example pool design pattern
*/
Class Pool
{
private $free = [], $occupation = [];
/**
* @return mixed|Time
*
*
*/
function get()
{
if (count($this->free) == 0) {
$worker = new Time();
} else {
$worker = array_pop($this->free);
}
$this->occupation[spl_object_hash($worker)] = $worker;
return $worker;
}
/**
* @param $worker
*
*
*/
function dispos($worker)
{
if (isset($this->occupation[spl_object_hash($worker)])) {
unset($this->occupation[spl_object_hash($worker)]);
$this->free[spl_object_hash($worker)] = $worker;
}
}
/**
* @return int
*
*/
function count()
{
return count($this->free);
}
}
/**
* Class Time
*
*
*/
class Time
{
/**
* @return DateTime
*
*/
function getTime()
{
return new DateTime();
}
}
$pool = new Pool();
$worker1 = $pool->get();
$worker2 = $pool->get();
$worker3 = $pool->get();
/**
*
* dispos $workers
*/
$pool->dispos($worker1);
$pool->dispos($worker2);
print_r($pool->count());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment