Last active
November 26, 2015 09:19
-
-
Save smichaelsen/7fc60e9bd2eeeb647ce4 to your computer and use it in GitHub Desktop.
Example how to use the TypeInterface to let extbase initialize objects from your database records
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 AppZap\MyExt\Type; | |
use TYPO3\CMS\Core\Type\TypeInterface; | |
/** | |
* In our application we have fields that store time intervals as minutes in the database. | |
* In our code we want proper DateInterval objects, so we use a TypeInterface to let extbase take care of the conversion. | |
* | |
* Usage example on a model property: | |
* | |
* /** | |
* * @var \AppZap\MyExt\Type\DateInterval | |
* * / | |
* protected $duration; | |
* | |
*/ | |
class DateInterval extends \DateInterval implements TypeInterface | |
{ | |
/** | |
* Constructs a DateInterval object from the minutes coming from the database | |
* @param string $minutes | |
*/ | |
public function __construct($minutes) | |
{ | |
parent::__construct('PT' . (int)$minutes . 'M'); | |
} | |
/** | |
* Returns the minutes for the DateInterval to store it in the database | |
* @return string | |
*/ | |
public function __toString() | |
{ | |
return (string)round($this->toSeconds() / 60); | |
} | |
/** | |
* @return int seconds | |
*/ | |
protected function toSeconds() | |
{ | |
$reference = new \DateTimeImmutable; | |
$endTime = $reference->add($this); | |
return $endTime->getTimestamp() - $reference->getTimestamp(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment