Because the markup generation is fairly simple when only using one event, all this method will do is load the desired event by its ID using _loadEventData and then return the first—and o
Trang 1Because the markup generation is fairly simple when only using one event, all this method will do is
load the desired event by its ID using _loadEventData() and then return the first—and only, due to the
LIMIT 1 clause—result from the method
Add the following method to the Calendar class:
<?php
class Calendar extends DB_Connect
{
private $_useDate;
private $_m;
private $_y;
private $_daysInMonth;
private $_startDay;
public function construct($dbo=NULL, $useDate=NULL) { }
public function buildCalendar() { }
private function _loadEventData($id=NULL) { }
private function _createEventObj() { }
/**
* Returns a single event object
*
* @param int $id an event ID
* @return object the event object
*/
private function _loadEventById($id)
{
/*
* If no ID is passed, return NULL
*/
if ( empty($id) )
{
return NULL;
}
/*
* Load the events info array
*/
$event = $this->_loadEventData($id);
/*
* Return an event object
Trang 2*/
if ( isset($event[0]) )
{
return new Event($event[0]);
}
else
{
return NULL;
}
}
}
?>
When called, this method will return an object (for the ID of 1) that looks like this:
Event Object
(
[id] => 1
[title] => New Year's Day
[description] => Happy New Year!
[start] => 2010-01-01 00:00:00
[end] => 2010-01-01 23:59:59
)
Creating a Method to Generate Markup
Now that an array of a single event’s data is available, you can build a new public method to format the event data into HTML markup
This method will be called displayEvent(); it will accept an event’s ID and generate HTML markup
using the following steps:
1 Load the event data using _loadEventById()
2 Use the start and end dates to generate strings to describe the event
3 Return the HTML markup to display the event
Create the displayEvent() method by adding the bold code to the Calendar class:
<?php
class Calendar extends DB_Connect
{
private $_useDate;
private $_m;
private $_y;
Trang 3private $_daysInMonth;
private $_startDay;
public function construct($dbo=NULL, $useDate=NULL) { }
public function buildCalendar() { }
/**
* Displays a given event's information
*
* @param int $id the event ID
* @return string basic markup to display the event info
*/
public function displayEvent($id)
{
/*
* Make sure an ID was passed
*/
if ( empty($id) ) { return NULL; }
/*
* Make sure the ID is an integer
*/
$id = preg_replace('/[^0-9]/', '', $id);
/*
* Load the event data from the DB
*/
$event = $this->_loadEventById($id);
/*
* Generate strings for the date, start, and end time
*/
$ts = strtotime($event->start);
$date = date('F d, Y', $ts);
$start = date('g:ia', $ts);
$end = date('g:ia', strtotime($event->end));
/*
* Generate and return the markup
*/
return "<h2>$event->title</h2>"
"\n\t<p class=\"dates\">$date, $start—$end</p>"
"\n\t<p>$event->description</p>";
}
private function _loadEventData($id=NULL) { }
Trang 4private function _createEventObj() { }
private function _loadEventById($id) { }
}
?>
Creating a New File to Display Full Events
To display the output of displayEvent(), you’ll create a new file This file will be called view.php, and it will reside in the public folder (/public/view.php)
This file will be called with a query string containing the ID of the event to be displayed If no ID is supplied, the user will be sent back out to the main view of the calendar
At the top of view.php, check for an event ID, and then load the initialization file; the page title and CSS file are set up in variables, and the header file is called After that, a new instance of the Calendar
class is created
Next, set up a new div with the ID of content and call the displayEvent() method Add a link to go
back to the main calendar page, close the div, and include the footer
All things considered, the file should end up looking like this:
<?php
/*
* Make sure the event ID was passed
*/
if ( isset($_GET['event_id']) )
{
/*
* Make sure the ID is an integer
*/
$id = preg_replace('/[^0-9]/', '', $_GET['event_id']);
/*
* If the ID isn't valid, send the user to the main page
*/
if ( empty($id) )
{
header("Location: /");
exit;
}
}
else
{
/*
* Send the user to the main page if no ID is supplied
*/
header("Location: /");
exit;
}
Trang 5/*
* Include necessary files
*/
include_once ' /sys/core/init.inc.php';
/*
* Output the header
*/
$page_title = "View Event";
$css_files = array("style.css");
include_once 'assets/common/header.inc.php';
/*
* Load the calendar
*/
$cal = new Calendar($dbo);
?>
<div id="content">
<?php echo $cal->displayEvent($id) ?>
<a href="./">« Back to the calendar</a>
</div><! end #content >
<?php
/*
* Output the footer
*/
include_once 'assets/common/footer.inc.php';
?>
Test this file by going back to the main calendar and clicking an event title The view.php file loads
and displays the event information in a format that matches the calendar (see Figure 4-8)
Trang 6Figure 4-8 The event information displayed after clicking an event title
Summary
You now have a fully functional events calendar, which you created using object-oriented PHP and MySQL Along the way, you learned how to handle dates, how to organize entries into objects for easy access, and how to output markup and stylesheets to resemble a traditional calendar In the next chapter, you’ll build controls to add, edit, and create events
Trang 7■ ■ ■
Add Controls to Create, Edit,
and Delete Events
Now that the calendar can be viewed, you need to add controls that will allow administrators to create, edit, and delete events
Generating a Form to Create or Edit Events
To edit an event or add new events to the calendar, you need to use a form You do this by adding a
method called displayForm() that generates a form for editing and creating events to the Calendar class
This simple method accomplishes the following tasks:
1 Checks for an integer passed as the event ID
2 Instantiates empty variables for the different fields used to describe events
3 Loads event data if an event ID was passed
4 Stores event data in the variables instantiated earlier if it exists
5 Outputs a form
■ Note By explicitly sanitizing the event ID passed in the $_POST superglobal, you ensure that the ID is safe to use since any non-integer values will be converted to 0
You build the displayForm() method by adding the following bold code to the Calendar class:
<?php
class Calendar extends DB_Connect
{
private $_useDate;
private $_m;
Trang 8private $_y;
private $_daysInMonth;
private $_startDay;
public function construct($dbo=NULL, $useDate=NULL) { } public function buildCalendar() { }
public function displayEvent($id) { }
/**
* Generates a form to edit or create events
*
* @return string the HTML markup for the editing form */
public function displayForm()
{
/*
* Check if an ID was passed
*/
if ( isset($_POST['event_id']) )
{
$id = (int) $_POST['event_id'];
// Force integer type to sanitize data
}
else
{
$id = NULL;
}
/*
* Instantiate the headline/submit button text
*/
$submit = "Create a New Event";
/*
* If an ID is passed, loads the associated event */
if ( !empty($id) )
{
$event = $this->_loadEventById($id);
/*
* If no object is returned, return NULL
*/
if ( !is_object($event) ) { return NULL; }
$submit = "Edit This Event";
Trang 9}
/*
* Build the markup
*/
return <<<FORM_MARKUP
<form action="assets/inc/process.inc.php" method="post">
<fieldset>
<legend>$submit</legend>
<label for="event_title">Event Title</label>
<input type="text" name="event_title"
id="event_title" value="$event->title" />
<label for="event_start">Start Time</label>
<input type="text" name="event_start"
id="event_start" value="$event->start" />
<label for="event_end">End Time</label>
<input type="text" name="event_end"
id="event_end" value="$event->end" />
<label for="event_description">Event Description</label>
<textarea name="event_description"
id="event_description">$event->description</textarea>
<input type="hidden" name="event_id" value="$event->id" />
<input type="hidden" name="token" value="$_SESSION[token]" />
<input type="hidden" name="action" value="event_edit" />
<input type="submit" name="event_submit" value="$submit" />
or <a href="./">cancel</a>
</fieldset>
</form>
FORM_MARKUP;
}
private function _loadEventData($id=NULL) { }
private function _createEventObj() { }
private function _loadEventById($id) { }
}
?>
Adding a Token to the Form
If you look at the preceding form, there’s a hidden input named token that holds a session value, also
called token This is a security measure to prevent cross-site request forgeries (CSRF), which are form
submissions that are faked by submitting a form to your app’s processing file from somewhere other
than the form itself This is a common tactic used by spammers to send multiple forged entry
submissions, which is annoying, potentially harmful, and definitely undesirable
Trang 10This token is created by generating a random hash and storing it in the session, and then posting the
token along with the form data If the token in the $_POST superglobal matches the one in the $_SESSION
superglobal, then it’s a reasonably sure bet that the submission is legitimate
You add an anti-CSRF token into your application by modifying the initialization file with the code shown in bold:
<?php
/*
* Enable sessions
*/
session_start();
/*
* Generate an anti-CSRF token if one doesn't exist
*/
if ( !isset($_SESSION['token']) )
{
$_SESSION['token'] = sha1(uniqid(mt_rand(), TRUE));
}
/*
* Include the necessary configuration info
*/
include_once ' /sys/config/db-cred.inc.php'; // DB info
/*
* Define constants for configuration info
*/
foreach ( $C as $name => $val )
{
define($name, $val);
}
/*
* Create a PDO object
*/
$dsn = "mysql:host=" DB_HOST ";dbname=" DB_NAME;
$dbo = new PDO($dsn, DB_USER, DB_PASS);
/*
* Define the auto-load function for classes
*/
function autoload($class)
{
$filename = " /sys/class/class." $class ".inc.php";
if ( file_exists($filename) )
{
include_once $filename;
}