Created
June 19, 2014 17:20
-
-
Save karptonite/8af0e47a256c18b12aec to your computer and use it in GitHub Desktop.
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 | |
namespace Geek\Cache; | |
class CacheBuilder | |
{ | |
private $cache; | |
private $memocache; | |
private $tagsetfactory; | |
public function __construct( Cache $cache, Cache $memocache, TagSetFactory $tagsetfactory, array $stack = null ) | |
{ | |
$this->cache = $cache; | |
$this->memocache = $memocache; | |
$this->tagsetfactory = $tagsetfactory; | |
$this->stack = $stack ?: array( function() use( $cache ){ return $cache; } ); | |
} | |
public function make() | |
{ | |
$stack = $this->stack; | |
$cache = $this->cache; | |
while( $factory = array_shift( $stack ) ) | |
$cache = $factory( $cache ); | |
return $cache; | |
} | |
private function addToStack( callable $factory ) | |
{ | |
$stack = $this->stack; | |
$stack[] = $factory; | |
return new self( $this->cache, $this->memocache, $this->tagsetfactory, $stack ); | |
} | |
public function memoize() | |
{ | |
$memocache = $this->memocache; | |
$factory = function( $cache ) use ( $memocache ){ | |
return new MemoizedCache( $cache, $memocache ); | |
}; | |
return $this->addToStack( $factory ); | |
} | |
private function getSoftInvalidatableFactory( $policy ) | |
{ | |
return function( $cache ) use ( $policy ){ | |
if( $cache instanceof SoftInvalidatable ) | |
return new SoftInvalidatableCache( $cache, $policy, $cache ); | |
else | |
return new SoftInvalidatableCache( $cache, $policy ); | |
}; | |
} | |
public function addTags( array $tags ) | |
{ | |
$tagsetfactory = $this->tagsetfactory; | |
$tagset = $tagsetfactory->makeTagSet( $tags ); | |
$policy = new TaggedFreshnessPolicy( $tagset ); | |
$factory = $this->getSoftInvalidatableFactory( $policy ); | |
return $this->addToStack( $factory ); | |
} | |
public function addGracePeriod( $gracePeriod = null ) | |
{ | |
$policy = new GracePeriodFreshnessPolicy( $gracePeriod ); | |
$factory = $this->getSoftInvalidatableFactory( $policy ); | |
return $this->addToStack( $factory ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment