Groovy things #2

In the process of writing my post yesterday, I realised that the biggest annoyance of Groovy is really its type system. Today, I came across this, ahm, surprising, string-to-integer conversion:

class A {
  String abc = "1"
  int getAbc() {
    return abc
  }
}
def a = new A()
println a.getAbc() // prints ... "49" ?!?

class B {
  String abc = "1"
  int getAbc() {
    return abc.toInteger()
  }
}
def b = new B()
println b.getAbc() // prints "1"

By the way, if the string is “2″ in the first example, you get …. 50. Tada!
Well I don’t know about you, but I’ll be rather glad when I have finished the coursework (which is the only reason why I use Groovy … we have to), which should be soon :)

March 31, 2011 | No Comments

Not so Groovy

I can’t believe my last post is from before when I started my MSc course in London. Anyway, without making up more excuses for that, I’ll move to the actual topic of this blog post: the Groovy programming language. Which turns out not to be so groovy …

From the Groovy website, it “is an agile and dynamic language for the Java Virtual Machine”. An agile language? Ahm … whatever. Unfortunately, things don’t get better.

First of all, you almost find no information on groovy outside their official website, and the stuff on their is badly organized and rarely of any use.
Then, there is still all that Java stuff. Want to create a collection of something? Oh yeah, there’s Map, List, Array, ArrayList, Collection, Set … I mean, seriously? Probably there even more types, but it’s hard to find out in the docs. Oh how I love JavaScript: Object. That’s it.
But the thing that bugs me most is the language itself: It feels so extremily fragile and buggy. I never thought of a programming language in these terms before, I would have used those terms for software only. I think one reason for this is Groovy desire to be smart or”groovy”. Let’s have a look at an example: The type system and meta programming.

Say you have this class:
class A { void print(String message) { println message } }
With meta programming, you can add another method like so:
A.metaClass.shout = { message -> println message.toUpperCase() } }
Oh, actually, it’s a closure and not a method, and Groovy has extra syntax for closures … Anyway, not going into that, let’s try it:
def a = new A()
a.print("Hello World") // prints "Hello World"
a.shout("Hello World") // prints "HELLO WORLD"

Okay, so long this is nice, but here things become weird. Say we want to replace a method (which would be very useful in unit tests):
A.metaClass.print = { message -> }
def a = new A()
a.print("Hello World")

If you would expect that nothing gets printed now, you’re wrong! Calling print still gives you “Hello World”. Hmm … Too bad. Why is the method not replaced? After some time, I changed my class to this:
class A { void print(message) { println message } }
Notice the difference? message is not typed anymore. Applying the meta trick again now results in:
A.metaClass.print = { message -> return "" }
def a = new A()
a.print("Hello World") // prints "Hello World"

Yep. Really. Okay, to be honest, it works if you type the closure as well. But here’s the thing: This weird mixture of handling type very lax but then again very tightly is a constant source of confusion. Either have a static type system, or have a dynamic one. But please, not both! I can’t count how often I stumbled upon this and similar issues in the last days … Unfortunately, Groovy is full of this “smart” behaviour that is destined to get in your way …

Dear language designers: Leave it to the programmer to be smart and make an easy language with only a handful of concepts. Not a myriad of concepts and hundreds of “smart things” to remember. Actually, that’s something that JavaScript gets completely right …

And dear programmers: Spare yourself some hair pulling and avoid Groovy.

March 30, 2011 | 2 Comments

Moving On

It has been pretty quiet here lately … actually I haven’t written anything since June! So what have I been up to?
First of all, I finished my bachelor studies in Austria – yay! I wanted to start working afterwards, but somehow my plans changed again and now I’m about to study one more year. This came a bit unexpected cause I thought there were no master studies which would interest me, but then I stumbled over Information and Web Technologies in London. Which means I’ll be in London starting next month! There’s only one thing left to do: Passing the IELTS test tomorrow ;)
Besides that, I was travelling quite a bit in the past months (good old Germany, Austria, Hungary, …), which was fun and I’m looking forward to do some more travelling, and maybe also some more hiking in the Alps. Hope this works out, before I leave European mainland …
Anyways, all of this stopped me from doing lots of programming, which is more or less the reason for no updates to this blog. I guess I’ll be writing more during my studies in London, but as nothing is set in stone yet, let’s see how this turns out :)

August 20, 2010 | 1 Comment

Weiter denken

Heute mal was Politisches, und weils Deutschland betrifft, auf deutsch. Also, die Tagesschau fragt in einem Kommentar: Wer lebt denn hier über seine Verhältnisse? Und es folgt eine Anklage an den Staat, bei der klar gemacht wird, dass der Durchschnittsbürger nicht mehr ausgibt, als er einnimmt; also nicht maßlos lebt.

Ich möchte nun dem Kommentator die Antwort geben, die er selbst andeutet. Es ist ganz einfach, der Staat lebt über seinen Verhältnissen. Und? Jetzt? Könnte es nicht sein, dass die Regierung genau das mit ihren Worten meint?! Der Staat lebt über seinen Verhältnissen. So einfach ist das.

Aber, bleiben wir mal nicht hier stehen, wie es der Kommentator und die Tagesschau gerne hätten, sondern denken weiter. Macht sich manchmal ganz gut.

Also: Der Staat lebt über seinen Verhältnissen. Heißt: Er muss weniger Geld ausgeben oder mehr einnehmen. Da der Staat dummerweise kein Unternehmen ist, kann er kein Geld verdienen. Alles Geld, dass er ausgeben kann, nimmt er sich vorher von seinen Bürgern. Alternative 1 ist also: Steuern erhöhen. Das mag natürlich kein Bürger, versuchen wir lieber Alternative 2.

Alternative 2: Der Staat gibt weniger aus. Und da kommen wir wieder zu dem Kommentar zurück. Ich zitiere:

“Meinen Sie vielleicht die Arbeitslosen und Hartz IV-Bezieher, bei denen jetzt gekürzt werden soll? Meinen Sie die Zeit- und Leiharbeiter, die nicht wissen, wie lange sie ihren Job noch haben?”

Und wieder ein Ja. Die meint die Regierung. Weiterdenken: Die unterstützt der Staat bisher. Wie effektiv, sei mal dahingestellt. Sparen (Alternative 2) heißt aber, weniger Geld auszugeben. Und damit trifft es die Armen, die das Geld bisher hauptsächlich bekommen (nur mal festgestellt, heißt nicht ich grundsätzlich dagegen bin, dass sie Unterstützung bekommen).

Oder z.B. dieser Satz: “Zum Beispiel die Politik, die unfassbare Schuldenberge aufhäuft und dann in Sonntagsreden über “Generationengerechtigkeit” schwadroniert”. Meint er der Großteil des Gelds geht auf die Politik an sich drauf? Wenn nicht, für was denn dann bitteschön?

Oder die erwähnte Abwrackprämie: Nur zum Spaß hat die keiner eingeführt. Es steckt das Ziel dahinter, Autobauer und damit Arbeitsplätze zu retten. Die Intention ist gut, ob es das richtige Mittel ist, steht natürlich auf einem anderen Blatt.

Also, bitte: Wer sich darüber aufregt, dass der Staat über seinen Verhältnissen lebt, sollte sich auch im Klaren sein, dass die Alternative entweder mehr Geld an den Staat oder weniger Geld vom Staat heißen. Und das wiederum heißt, das es unter anderem die trifft, die der Staat mit seinem Über-den-Verhältnissen-leben versucht zu unterstützen. Das ist zwar traurig, aber nun mal die Realität.

Denn Fakt ist: So wie der Staat momentan ist, können wir uns ihn nicht leisten. Klar sollte auch Bürokratie abgebaut werden, damit weniger Geld durch die Politik an sich ausgegeben wird. Doch wirklich saniert kann der Staat nur werden, wenn alle kürzer treten. Denn lasst uns nicht vergessen: Der Staat sind immer noch wir Bürger.

Und nicht zuletzt: Es wäre schön, wenn die Medien ab und zu weiter denken würden. Solch halbgares – bei Politikern würde man sagen populistisches – Zeug hilft keinem, sondern schafft nur Stimmung gegen eine Regierung, die nun, egal was sie macht, nur falsch handeln kann.

June 7, 2010 | No Comments

Reviewing

Today I’m going to review two things at once: The book Domain Driven Design by Eric Evans, and our semester project Quizmaker. They both have a lot in common, so why not combine two reviews in one blog post?

After I started to dive into FLOW3, I began to read the recommended book, Domain Driven Design by Evans. It took me quite a while to finish it, but I made it last week. Yay! And it was well worth it. If you’re interested in object oriented programming, you should read it, too. It’s not focused on any specific language, although it’s obvious that it best fits Java-style like languages (all the examples are in Java, too). The book emphasizes the need to find good solutions and to constantly refine them. Evans even argues that good design can only evolve and can never be achieved before actual code is written. Although most of the book is really interesting, I found the greatest value to be in the part about ubiquotus language, because I could relate to it in my current situation: the semester project Quizmaker. In short, ubiquotus language is all about creating a shared understanding of the problem and the things involved. The ubiquotus language should be used by all team members and even by the client. If some terms are unclear or client and programmer communicate in a different language, these differences should be eliminated.

But let me introduce the project. Our group of six students had the task to create a web-based training which creates a quiz based on a XML-file. The whole Quizmaker is written in ActionScript (making heavy use of the Flex framework). Although the task didn’t sound too complicated in the beginning, we once again discovered that the devil is in the details. For example, providing a good visual feedback when a question is answered can be really tricky. Combine that with some user interaction (events … always good for surprises) and some shortcomings of Flex, and you get a nice mix ;). But, today we finished most of it and now we’re looking forward to see it used by our employer!

Now why is this project actually connected to Domain Driven Design (DDD)?. Well, we didn’t talk about designing it domain-driven, but because I’ve been the developer lead, I tried to bring as much of it in as applicable, as well as to look out for problems mentioned in the book. One of the really obvious things was aforementioned ubiquotus language. For example, at the beginning we simply weren’t talking about the same things. We talked about “the feedback” and “the feedback in the end”. This led to question like: “Which feedback are you talking about now?” And then, after some time, it hit me: We had an abstract question class and a training class (containing all questions of one training) already. Why not talk about “question feedback” and “training feedback”? I proposed that to the group and from then on we never had this problem again. It sounds really really obvious when writing about it, but somehow we didn’t have these clear terms in the beginning. But once we identified the problem, it was easy to come up with a ubiqutuos language in this area, and it helped a lot in our discussions later on.

Another important take-away from DDD was the focus on constant refinement, and I tried to look out for possible breakthroughs. When we started out, we divided our project into 3 groups (so that we could do pair programming in the beginning), each responsible for one part of MVC: Model, View and Controller. It was a good start, enabling us to work on separate functionality, but soon we realized that our design with View and Controller was awkard. It took us a while to realize this, but finally I had a look at how people were solving similar problems to ours. The key was to question the MVC pattern itself, or more specifically the use of a traditional Controller in Flex. This was when I discovered the Code-Behind pattern (which actually is a lot like a Controller, but fits better to Flex), which we implemented then. This made our code a lot simpler, while keeping a clean separation between code and presentation.

All in all, we had a lot of fun during the project (despite some Flex crazyiness), and it was nice to see how lessons learned from the book could be applied quite easily in “real life” :)

June 1, 2010 | No Comments

Rethinking

I think it’s finally time to write about my new view of TYPO3 (which is not that new anymore actually). I’ve written several times about TYPO3 or FLOW3 in the last months and this might come as a surprise to those who know me. Because if you do, then you know that I didn’t like TYPO3 at all.

When I started working on the web, I quickly realized that I needed a CMS for the website that I built. And as I knew PHP, I started to write one my own (actually, it wasn’t a decision as structured as it sounds, it just came to happen). And yes, it was horrible in the beginning, but it worked. I also got to know Mambo (which is now better known as the fork Joomla) and later on, TYPO3. Both experiences made me even more convinced that writing my own CMS was a good idea. Because they were even more horrible in my eyes: they were bloated and had a bad usability. Over time, my programming skills improved and the code base of my CMS became object oriented. And you could do a lot of things with a very simple backend interface: any layout I can think of was possible, extensions were easy to write and you could assign various permissions to different users just to name a few features. All of this while the code stayed simple and small. And of course it had the advantage that I knew every part of the system. For example, writing extensions for another system was a lot more hassle for me. So all in all, I was happy with my solution and it is still used in a couple of websites as of today.

But as the title of this post suggests, I came to rethink my general opinion. Here’s why:

  1. There is the problem that maintaining my own CMS is a lot of work (although this was good in the beginning, because I really learned a lot about programming from working on it). Also, as distribution grows, I would need to document the project and and it would be hard to just withdraw from the project when I can’t or don’t want to develop it anymore.
  2. It will never have the same feature set and possibilities as some big CMS out there backed by a community.
  3. It doesn’t make sense job-wise: In the long run, either I’m working full-time on my CMS or I’m starting to learn another, widely used CMS and abondon my own.
  4. I came to the conclusion that big and even fat systems might not be that bad after all. Once you know such a system, you can use it for nearly every website you need to built. Many people argue that you don’t need most of the features for a majority of websites and therefore should use smaller, more tailored systems. I disagree. It’s a better use of resources to learn everything about one system than to know only bits and pieces about several systems. And if you build a small website that doesn’t need most of the features of your system, so what?

Although those reasons would be enough for me to change my mind now, they weren’t the trigger. It all happened because I discovered FLOW3. It was all that I dreamed of and many things that I haven’t even dreamed about! It was just so close to what I wanted to build that it didn’t make sense to build it myself anymore. And if this is what’s coming up for TYPO3, it seems to be a good choice as a CMS. Moreover, as TYPO3 v5 is just about to take shape, I have the chance to know the system in depth before it goes live. I already feel quite comfortable using FLOW3 and I’m looking forward to program extensions for TYPO3. Besides, it’s a good choice job-wise: most agencies in Middle Europe use it.

So where does that leave us? I’ll still maintain the websites that use my own system, but I won’t develop it anymore. And as time goes on, I might switch the engine to TYPO3. Probably not before version 5 is out because I think version 4 still sucks a lot. And there is no real need to stop using my CMS, it works fine. It just reached the end of it’s capabilities. Don’t get me wrong: I’d love to develop my own CMS further, implement my ideas and see how well I can do. But I came to the conclusion that it’s pointless to a certain degree as it will never be able to compete with big systems unless I’m working full-time on it.

And that’s why I’m hoping that FLOW3 / TYPO3v5 will be so good that I never wish to write my own system again.

May 18, 2010 | No Comments

Travelling through Date and Time, part IV

Welcome to the fourth installment of my series about date and time in PHP. Let’s review what we’ve done so far: In the first part, we looked at the basics (DateTime object and friends). Then, we applied the theory and discussed the basic outline for an application in FLOW3. Finally we dealt with the until-then omitted timezones. Still, there is one important thing that is missing. It could be summarized by the following question: What does 07/09/08 mean? Well, yes, it’s a date, but it could be a very different date depending how you interpret it. Personally, I’m always confused when I come across a date formatted differently to what I’m used to … Which leads us to today’s topic: We need localization in order to make it easy for everyone to understand the dates in our application.

How do we do this? Unfortunately, this time it’s not that clear. Basically, you have two options to consider: strftime and IntlDateFormatter. We’ll have a look at both and will see advantages and disadvantages of both approaches. But, first and foremost, they have one thing in common: They don’t work with DateTime. What the … ? Yes. But at least they both work with timestamps ;)

Let’s start with IntlDateFormatter. This class was introduced in PHP 5.3 and is only available if the PECL extension intl is installed. To use it, you need to define a format object first, like this:
$enUSFormat = new IntlDateFormatter('en_US', IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'America/New_York', IntlDateFormatter::GREGORIAN);
To find out more about the options, please refer to the docs.
Finally, you can use this format object to get a localized output of a timestamp like so:
$enUSFormat->format($myDateTime->getTimestamp());
If you want to have more/full control about the format used, you can also specify a pattern at the end:
$enUSFormat = new IntlDateFormatter('en_US', IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'America/New_York', IntlDateFormatter::GREGORIAN, 'MM/dd/yyyy');
Possible patterns can be found on the ICU website.

The other option is to go with strftime. It’s the traditional way of doing things, and, in contrast to IntlDateFormatter, it is locale aware. That means that the output depends on the locale setting, which can be changed like this:
setlocale(LC_TIME, 'en_US');
Note that either LC_ALL (locale setting for all localization areas) or LC_TIME (only for date/time formatting) works fine here.
Then, you can use strftime like this:
strftime('%c', $myDateTime->getTimestamp());
%c is just one of the formatting options you have. There are a lot more available which offer possibilities similar to IntlDateFormatter’s pattern string. Again, for more information, please refer to the docs.

To conclude, which option should be used? I’d opt for strftime. Mainly because it is available on all PHP setups (a big point in my opinion), and also because it is easier to use in conjunction with setlocale. The disadvantage of strftime is that it uses a different format string than date() or DateTime::format() in contrast to IntlDateFormatter.

With this, I’m going to end my journey through date and time in PHP. I hope you enjoyed it!

, | April 24, 2010 | No Comments

Travelling through Date and Time, part III

Until now, we looked at the basics and started to work with our dates. But we didn’t deal with timezones, which means all we did was pretty useless. In this part, we’re going to change that.

Okay, so what exactly are timezones? According to Wikipedia, a timezone “is a region of the earth that has uniform standard time, usually referred to as the local time”. And “local time” could be defined like this: “local time is UTC plus the current timezone offset for the considered location”. Note that it says “current offset”, not just “offset”, because a location can have different offsets at different times (e.g. because of daylight savings time). By the way: UTC stands for “Coordinated Universal Time” (actually: “Universal Time, Coordinated”) and is roughly equivalent to the formerly used GMT (Greenwich Mean Time). It is considered to be the “world time”, on which basis all other timezones are calculated. More on this topic can be found on Wikipedia, but I think this will do for our task ;)

In part I and II we completely omitted the fact that we live in timezones. Let’s have a closer look at what happened when we didn’t specify a timezone along with our dates. Or did we? Since PHP 5.3, there is a php.ini setting for the default timezone, e.g.: date.timezone = 'Europe/Berlin'. Actually, if you haven’t set that and are using something like date(), you’ll get a warning. But in case this is set, all DateTime objects without any specific timezone are implicit in the timezone set in the php.ini. So, in my setup, my dates would have been in Europe/Berlin, but the very same script could produce completely different results in your setup. Which could cause problems.

But it’s not all bad. Remember the definiton in the beginning? Every local time is computed by UTC plus current offset. So all things are in relation to UTC. And the unix timestamp, which we got to know in the first part of this series, is always in UTC. This proves really helpful. Let’s see why:
Say we create a DateTime object, this time with a specific timezone, like this:
$dateInBerlin = new DateTime('2010-04-20 10:00:00', new DateTimeZone('Europe/Berlin'));
And another date:
$dateInMoscow = new DateTime('2010-04-20 12:00:00', new DateTimeZone('Europe/Moscow'));
On April 20th, the timezone offset from Berlin to UTC is 2 hours, and from Moscow to UTC is 4 hours, so the difference between Berlin and Moscow timezone is 2 hours. Note that our dates are not exactly the same: One is at 10:00, the other at 12:00. Now, if we call getTimestamp() on both objects, we’ll get the same timestamp (1271750400) for both dates. Why? Because the timestamp consists of seconds elapsed since January 1st 1970 in UTC timezone. And because of the time difference between Berlin and Moscow, the dates are the same when expressed in UTC time.

OK, what does that mean for us? As we already know, FLOW3 stores the DateTime objects in the database as unix timestamps. To convert the DateTime object to an integer, FLOW3 uses the getTimestamp() method. Therefore, whatever timezone our date is in, we’ll get the same timestamp. What happens on reconstitution? The timestamp in the database is set via setTimestamp(). At this point, we’ll have a DateTime which value is the timestamp (UTC) and which expresses this in the default timezone specified in the php.ini.
But because I want to store a timezone along with my events, we need to do something before displaying them. We need to make sure that format() uses my timezone and not the default timezone. It turns out this is actually quite easy to do. DateTime objects have the method setTimezone(), which expects a valid timezone identifier as an argument. It then modifies the timezone, but not the timestamp. This is very important, as format() will output something different now, but getTimestamp() will still be the same. Mission accomplished.

Which means all is well. Or is it? No, not quite. Because if we want to associate a timezone with an event, we’ll probably have a form which allows the input of a date, along with a dropdown of possible timezones. Of course, the user enters the date corresponding to the timezone he selected. So before saving the date, we have to convert the entered date to express the correct timestamp (which is: an UTC expression of the combination of entered date and selected timezone). Note that just setting the timezone via setTimezone() doesn’t work here, because we actually want to modify the timestamp inside the DateTime object. Of course, this conversion has only to take place if we create the DateTime object before we have the timezone information available. On the other hand, if we change the timezone after we set the date, we have to modify the date again.

The last bit shows that timezone handling can get a bit complicated, but what it comes down to is basically to make sure that all dates in the database are in UTC. Once that is ensured, we’re safe. Additionaly, we also solved the problem of different php.ini settings, as our solution is now independent of this setting.

Next up: Localization.

, , | April 22, 2010 | 1 Comment

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.

, , | April 20, 2010 | No Comments

Travelling through Date and Time, part I

This is the first part of a series (of yet-to-be-determined length) dealing with date and time in PHP (and FLOW3).

This first part will cover the very basics of this complex and often very weird topic. Please note that what you’ll read here is often not the whole story, and will be completed in the next parts.

So why am I doing this? Well, I’m trying to put together a calendar package for FLOW3. The calendar should be able to handle events which have a beginning and an optional end. A beginning consists of a date (year, month and day) and, again optional, a time (hour and minute, no seconds). The same applies for the end of an event. Furthermore, when creating an event, the admin should be able to specify the timezone of the dates entered (one timezone for both dates).

This blog post will only deal with the handling of date and time in PHP and FLOW3, I’ll leave the timezone handling for another time.
So, what do we have? Basically, when using date and time in PHP, we use DateTime. DateTime was introduced in PHP 5.2 and provides a way of dealing with, well, date and time. Unfortunately, DateTime is a bit weird. For example, there are at least 3 options to set the date and time of a DateTime objects.
One is to hand it a UNIX timestamp (since 5.3, via setTimestamp). This is the number of elapsed seconds since January 1st 1970, 00:00. In PHP, an integer is used for timestamps. On 32-bit systems, this will mean we’ll run into problems in 2038 because too many seconds will have passed by then to be hold in an 32-bit signed integer. Of course, probably all systems will be 64-bit by then, so not to worry on the PHP part here in my opinion.
A second option is to create the DateTime object with a string like 2010-04-15 17:06:02. You can use any string that you could also pass to strtotime. When you create a DateTime object with no arguments, the string "now" is assumed and you’ll get an object which represents the current date and time.
Weird enough, there is no method similar to setTimestamp to do the same thing later on an object, you have to use the static method DateTime::createFromFormat or use something like the add/sub methods to change the DateTime object later on …
Thirdly, you can use setDate and setTime to modify parts of a DateTime object.

Ok, now on to the next topic: Gettting the date and time back from the object. format() exists for this purpose, which takes a format string (with the same options as for date()). Unfortunately, there is no locale aware format method, but again, more on this in another blog post.

With this covered, what about FLOW3? Basically, handling DateTime objects is baked right into the persistence layer. But how is it persisted? Well, let’s take a step back and have a look at MySQL for a second.
There, you have several options: You can store a regular INTEGER (unix timestamp), or a DATETIME value (and some other options as well). The latter stores a STRING representation of a date and time, but has the advantage that you can do several operations in SQL like comparisons. The INTEGER version of course has the disadvantage that it could run into the 2038 problem mentiond earlier.
Now, back to FLOW3: The persistence backend is generating all SQL queries from the query object, so we can’t use the date/time comparisons. Also, some of these things are MySQL only anyway, so usage of them is not an option for FLOW3 which aims to be more or less backend independent. That means FLOW3 turns the DateTime object into a unix timestamp before persisting it (in an INTEGER field), and converts it back upon reconstitution.

Enough for today. The plan is to write more about handling and comparing DateTime values in FLOW3 in the next part. The third part will probably deal with timezones and then, we’ll have a look at localization.

, , | April 15, 2010 | No Comments