Here's the first in a mini-series dedicated to CakePHP3.

Remember in CakePHP 2 how we had the handy "created" and "modified" columns on a table, which were automatically populated when a record was created/updated? Not sure how to accomplish this in the latest and greatest version of Cake, CakePHP3? Today's quick tip will show you exactly that.

As explained above, in Cake2 all we had to do was add the correct columns to a table and the framework would automatically populate the values - in Cake3 however we need to use a behaviour to accomplish the same thing.

Creating your table object

Start by creating your table file in /src/Model/Table - in my case I'm going to create a table object for my 'posts' table. Create your file in the directory mentioned and name it PostsTable.php (Posts being the name of the table you're wanting to use this on).

Once you've created that, we need to setup the basic structure needed for a table object. This will look something like this:

namespace App\Model\Table;
use Cake\ORM\Table;

class PostsTable extends Table{

}

In your class we then need to create an initialize function which runs at any point the Posts controller is invoked.

namespace App\Model\Table;
use Cake\ORM\Table;

class PostsTable extends Table{
    public function initialize(array $config)
    {

    }
}

Inside your initialize function we then need to add our Timestamp behaviour.

public function initialize(array $config)
{
    $this->addBehavior('Timestamp');
}

And there we have it, it really is a piece of Cake. Sorry, I'll show myself out...

namespace App\Model\Table;
use Cake\ORM\Table;

class PostsTable extends Table{
    public function initialize(array $config)
    {
        $this->addBehavior('Timestamp');
    }
}

Thanks for reading, shares are very much appreciated! :)