1

I was taking a test and saw this function:

Class Object{
    use Timestampable;
}
$object= new Object();
$object->setCreatedAt(new DateTime());

I believe it was a trick question, because I don't find "timestampable" in the php manual.

I have seen references to it on stackoverflow, which got me confused to if it actually can be used. I know of timestamp in the MySQL database, but does this actually exist or have a use in PHP?

Community
  • 1
  • 1
Sol
  • 949
  • 1
  • 11
  • 23
  • 4
    It's part of a library, it's called Gedmo which then again is an extension of doctrine. It's not in the standard PHP, therefor also not documented. – Nytrix Apr 09 '17 at 17:28
  • 2
    to be more specific - it's part of some third-party library – u_mulder Apr 09 '17 at 17:29
  • 2
    In the case that you want to work with dates and timestamps and what not, use the `DateTime` class. It supports pretty much anything you'd like with it. – Nytrix Apr 09 '17 at 17:40
  • https://github.com/Atlantic18/DoctrineExtensions/blob/HEAD//doc/timestampable.md This really helped me find documentation.:) I added a link for more info in case someone else has this question. – Sol Apr 09 '17 at 19:17

2 Answers2

2

Timestampable is a so-called trait and is meant to help reuse code.

Let's say you have a bunch of entities and all of them have some common functionality, e.g. they all need $createdAt and $updatedAt fields. You could achieve this functionality by creating a common base class for all entities, but that wouldn't be great from architecture standpoint.

Instead you could create a trait:

trait Timestampable
{
    protected DateTime $createdAt;
    protected DateTime $updatedAt;   
    ...
}

And then use it like so:

class User
{
    use Timestampable;
}

Now User objects will have $createdAt field and any other fields or methods that are defined in the trait, just like they would be defined inside the User class. This way you don't need to repeat the same code in all of your classes.

Timestampable is one of more common traits, but obviously traits aren't limited to that. Here's an example of a more complete Timestapable trait.

I know this is a 4 year old question, but it was the top result on google, so thought it may be helpful for others.

mindaugasw
  • 1,116
  • 13
  • 18
1

The question on the test is not about a Timestampable function, that is just the example. The question is designed to your knowledge of abstract classes, interfaces and traits.

Tristanisginger
  • 2,181
  • 4
  • 28
  • 41