Skip to content

Instantly share code, notes, and snippets.

@m2sh
Last active January 29, 2016 06:01
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save m2sh/a823db479e8553b762dc to your computer and use it in GitHub Desktop.
Unix Time stamp for created & modified field in database cakephp 3

##UnixTimeStamp Behavior for CakePHP 3.x This is modified version of default CakePHP Timestamp Behavior but it save unix timestamp integer into created or modified fields
only changed return statement in timestamp method in default behavior

##Install Steps:

  1. Copy UnixTimestampBehavior.php in /src/Model/Behavior/ or in your plugin behavior
  2. Go to your table models in /src/Model/Table
  3. Add behavior in to Table initialize method :
    $this->addBehavior('UnixTimestamp');
  4. Done!
<?php
namespace App\Model\Behavior;
use Cake\ORM\Behavior\TimestampBehavior;
use Cake\I18n\Time;
class UnixTimestampBehavior extends TimestampBehavior
{
/**
* Get or set the timestamp to be used
*
* Set the timestamp to the given DateTime object, or if not passed a new DateTime object
* If an explicit date time is passed, the config option `refreshTimestamp` is
* automatically set to false.
*
* @param \DateTime $ts Timestamp
* @param bool $refreshTimestamp If true timestamp is refreshed.
* @return \Cake\I18n\Time
*/
public function timestamp(DateTime $ts = null, $refreshTimestamp = false)
{
if ($ts) {
if ($this->_config['refreshTimestamp']) {
$this->_config['refreshTimestamp'] = false;
}
$this->_ts = new Time($ts);
} elseif ($this->_ts === null || $refreshTimestamp) {
$this->_ts = new Time();
}
return intval($this->_ts->toUnixString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment