Generating a ‘year-at-a-time’ calendar with calendar.class.php
In the previous post announcing the release of calendar.class.php I gave a quick example of how the class could be used to easily output multiple months. That example showed an interface made up of the previous, current and next month. Generating a full year at a time is just as easy to accomplish using a simple for loop. Here’s how…
To start off, include calendar.class.php. For this example I’ll also make use of the class’s built in linking behavior. The class has the ability to make days link to a url with the selected date appended. This is useful for allowing you to “walk through” the dates on the calendar. In order to set this up the script needs to know to look for a date passed through $_GET. If the date is present we’ll pass that to the constructor as our selected date, if not the script will fall back to a hard coded default date (2007-09-21 in this example). Then the Calendar object is created with the supplied date.
require_once('calendar.class.php'); $date = ( isset($_GET['date']) )? $_GET['date'] : '2007-09-21'; $example = new Calendar($date);
Another feature of the class that was demonstrated in the previous post, is the ability to pass in an array of dates to highlight on the calendar. Since this is a simple array of dates, you could easily load the array with dates obtained from a database query.
$example->highlighted_dates = array( '2007-08-06', '2007-08-15', '2007-09-04', '2007-09-07', '2007-09-12', '2007-09-28', '2007-10-10', '2007-10-20' );
Semantically speaking, we can describe a year as an ordered list of months. So I’ll start an ordered list to hold the months as list items, and give it an ID so it can be styled with CSS.
To build the year, we simply need to step through the 12 months of the year with a for loop. When the output_calendar method is called without arguments it will use the date initialized by the constructor. However we can override that behavior by passing specific year and month values. So, each time through the loop we’ll create a new list item and call the output_calendar method with the year and then increment the month to the current count of the loop.
That begs the question, where does the year value come from. It could simply be hard coded but the calendar produced would be locked into a set year. To keep the calendar more dynamic we’ll make use of one of the variables calendar.class.php initializes for us.
When the Calendar object is created it breaks the date provided to the constructor into its component parts ($year, $month, $day) and makes them available. So we can access the selected year as $example->year and pass that to output_calendar to produce the correct month.
The only thing left is to close the ordered list, and the “year-at-a-time” view is ready to go.