Skip to content

Instantly share code, notes, and snippets.

@naveed125
Last active May 2, 2020 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naveed125/c430eaaf50a6682d47ec884ff7066ef0 to your computer and use it in GitHub Desktop.
Save naveed125/c430eaaf50a6682d47ec884ff7066ef0 to your computer and use it in GitHub Desktop.
Deliver on check to avoid background processing
<?php
/**
* Wizard represents an object that generates mana over time
*/
class Wizard {
private $mana = 0;
private $last_checked = 0;
private $max = 1000;
private $rate = 100;
/**
* Constructor initializes the timer
*/
public function __construct()
{
$this->last_checked = time();
}
/**
* Cash get function calculates since it was checked last time
* As you can see, no background processing required.
*/
public function getMana()
{
$diff = time() - $this->last_checked;
if ($diff > 0) {
$this->mana = min($this->max, $this->mana + ($diff * $this->rate));
$this->last_checked = time();
}
return $this->mana;
}
}
/*
* Test code to show deliver on check on action
*/
$gandolf = new Wizard();
print("Startig mana: {$gandolf->getMana()}\n");
$sleep = mt_rand(0, 10);
print("Sleeping for {$sleep} seconds\n");
sleep($sleep);
print("New mana: {$gandolf->getMana()}\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment