Skip to content

Instantly share code, notes, and snippets.

@nyamsprod
Last active August 29, 2015 14:04
Show Gist options
  • Save nyamsprod/34c54225c356f2e951d4 to your computer and use it in GitHub Desktop.
Save nyamsprod/34c54225c356f2e951d4 to your computer and use it in GitHub Desktop.
CacheItemInterface::setExpiration improved

For the moment the $ttl argument is :

  • an integer: it is interpreted as the number of seconds after which the item MUST be considered expired.
  • a DateTime: it is interpreted as the point in time after which the item MUST be considered expired.

As seen in this implementation example $ttl could be :

  • an integer: it is interpreted as the number of seconds after which the item MUST be considered expired.
  • a DateInterval: it is interpreted as the interval after which the item MUST be considered expired
  • a DateTimeInterface: it is interpreted as the point in time after which the item MUST be considered expired.
  • null: a default value MAY be used. If none is set, the value should be stored permanently or for as long as the implementation allows.

PRO:

  • It allows the addition of DateTimeImmutable and DateInterval as supported types

CONS:

  • Should we use DateTimeInterface (PHP5.5+) only or explicitly state DateTime (PHP5.2+) AND DateTimeImmutable (PHP5.5+) ?
  • DateTimeInterval means PHP 5.3+ only compatible PHP.

Adding others types raises the question for a minimal PHP version to be used with this PSR. Obviously using DateTime and namespace means the implicit minimal PHP version is PHP 5.3

TL;DR:

  • No change means other added types MUST be documented at the library level: less interoperability
  • Change means more flexibility at the interface level: more code for any library that wants to implement the Cache and higher PHP version requirement
<?php
namespace CacheLib;
use DateTime;
use DateTimeInterface;
use DateTimeInterval;
use Psr\Cache\CacheItemInterface
class CacheItem implements CacheItemInterface
{
private $defaultExpirationInterval = 300;
...
/**
* Sets the expiration for this cache item.
*
* @param int|\DateInterval|\DateTimeInterface $ttl
*
* @return static
* The called object.
*/
public function setExpiration($ttl = null)
{
if ($ttl instanceof DateTimeInterface) {
$this->expiration = $ttl;
return $this;
} elseif ($ttl instanceof DateTimeInterval) {
$this->expiration = (new DateTime)->add($ttl);
return $this;
}
$add = filter_var($ttl, FILTER_VALIDATE_INT, ['options' => [
'min_range' => 0,
'default' => $this->defaultExpirationInterval
]]);
$this->expiration = new DateTime($add . ' SECONDS');
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment