Travelling through Date and Time, part II

Now that we covered the basices in part I, let’s actually do something. I’ll explain how to fill the model with data and how to get specific models from the repository in FLOW3.

Before we begin, let’s create some classes: A DemoController which will showcase some of our calendar functionality. Then, we’ll need an AdminController with basic CRUD actions and corresponding Fluid templates. For the Domain, I’m going to use an Event model and an EventRepository. To make it simple, each event will only contain a start date (startDateTime), an end date (endDateTime) and a title (title) and the respective getters and setters.

Let’s start with the AdminController. The question that arises is: How to deal with our DateTime objects? Obviously, we can’t just display a DateTime object in a form textfield, and on the other end, we’ll receive a string from the form instead of a DateTime object. It would be easy if we could get and set a string for the date and also the time (I think it’s good to have two separate textfields for date and time). To be able to do this, let’s create the needed getters and setters: getStartDate/getEndDate and getStartTime/getEndTime. How do they work? The get*-methods return a formatted version of the DateTime objects (e.g. $this->startDateTime->format('Y-m-d');), the set*-methods receive a string from the form and call setDate/setTime on the DateTime objects (e.g. $this->startDateTime->setDate($year, $month, $day); – of course, the variables have to be extracted from the string). For all of this to work, we have to make sure that the DateTime objects are never null, so we have to initialize them in the constructor.

Problem solved, so now on to the repository. Here we need to create our own methods which return subsets of events. This is actually a bit tricky and I won’t go into much detail here. But let’s have a look at how it is supposed to work generally. I would suggest having one method which can return all events between a beginning and an end (of course, it should work with no beginning or no end as well). We’ll call it getBetween. This method would be called by several wrappers which themselves are easier to use in a controller. E.g., it would be handy to have getIn (which allows us to specify only, for example, a year and the method determines beginning and end automatically), getLatest (skipping beginning and setting end to the current date) and getUpcoming (skipping end and using the current date as end).

And how does getBetween work? Or more to the point, how does it compare the dates? As we’ve seen in part I, FLOW3 stores all DateTime objects as unix timestamps in the database, which means our method getBetween has to create timestamps from the given arguments beginning and end, which then can be compared to the values in the database.

filed under , , posted on April 20, 2010

Comments are closed.