PHP and Heredocs
by Daniel Smith
04/10/2003
PHP is wonderful for generating dynamic web pages. The ability to
combine the PHP, HTML, and SQL statements within a script provides a lot
of power. Combining everything in one file, however, can make a big
mess.
Having separate files for PHP classes, HTML blocks, and SQL statements
can go a long way towards cleaner, more understandable web application
design and implementation. This article explains the use of
heredocs and associative arrays in "resource files".
A Big Problem: Ugly Code
Many of us have encountered PHP code like this:
<?php
print "<html><head>";
print "<title>sample</title>";
print "</head>";
print "<body><p>List of photo table:</p>";
print "<table>\n";
$connection = mysql_connect("some_host", "some_user",
"some_password");
$the_db = mysql_select_db("our_db", $connection);
$result = mysql_query("select * from photo_table");
while ($current_line = mysql_fetch_assoc($result)) {
print "<tr>\n";
foreach ($current_line as $cur_field) {
print "<td>$cur_field</td>\n";
}
print "</tr>\n";
}
print "</table>";
...etc...
?>
This is a simple example, lacking JavaScript or fancy HTML/CSS, but you
can see how quickly things can get out of hand. Jumping between languages
can be fun for a quick and dirty script, but it's a nightmare to navigate
for anything substantial. You could go back and forth between separate
sections of HTML and PHP within a file, to eliminate using
print to produce HTML, but even this approach can be
messy.
Another problem is dividing the work. Look again at the example and
imagine a team consisting of a database person, a great client-side
HTML/UI designer, and you, the PHP coder in the middle of it all, trying
to glue everything together. How can the three of you make much progress
with everything stuck together in the same file?
When you extract hardwired HTML and SQL from your PHP application, you
give yourself a lot of flexibility. Start treating these separate parts
of an application as "resources" that can be loaded from separate files.
Among other benefits, separating these concerns allows you to easily
switch between different HTML UIs, each available in multiple languages.
Your database person can optimize statements without affecting the
client-side designer, and you can spend more time dealing with straight
PHP.
What technique should we use in our separate resource files to make
large blocks of SQL and HTML available to our PHP classes?
Heredocs!
Consider large chunks of HTML or SQL statements larger than a few
lines. How would you assign these to a variable? One approach is to
escape every quote:
$some_var = "select * from photos where comment =\"some comment\";";
That's a simple example. Once you start mixing single and double
quotes, for example, in names such as "O'Reilly", the potential for
missing backslashes increases.
Heredocs have no quote problems. They allow you to assign a variable
with one or more lines of text in a much more straightforward fashion. I
think of a heredoc as a "document, right here". Here is a simple example
of assigning a SQL statement to illustrate the syntax:
$sql_list_collections =<<<EOD
SELECT collection_id,collection_dir,title,description, cover_photo_id
FROM collection
ORDER BY collection_dir ASC;
EOD;
EOD can be thought of as "End Of Data". You can choose
any terminating string you wish, as long as it
- is consistent in the first and last lines of the assignment, and
- does not otherwise occur at the start of a line within the here
document.
My next example is much more complex and demonstrates the use of associative
arrays and quoting. I scrub input variables (checking them for
validity) from a form, and toss them into an associative array called
$VALS. Associative arrays make very convenient containers
for related variables that have been checked and need to be passed to
different functions.
$sql_insert_photo =<<<EndSQL
INSERT INTO collection (title, major_category, subcategory,
location, event_date, collection_dir)
VALUES ('{$VALS['title']}', '{$VALS['major_cat']}',
'{$VALS['subcat']}', '{$VALS['location']}',
'{$VALS['date']}', '{$VALS['unique_path']}');
EndSQL;
Heredocs allow you to concentrate on the contents of the variable,
worrying less about print statements and backslashes. For large blocks of
HTML, this is crucial. A client-side person can focus on what they're
doing, instead of getting involved with the PHP side of things.
Resources And Templates: Using Heredocs
Let's shift our focus to using include files. When a file is
included, we can pick up variables from it. Rather than dealing with
myriad variables, each resource I pick up from my include file becomes an
element in an array called $RSRC. Bear in mind that
once-defined, you will treat this array as read-only.
Let's look at a function within a PHP class that reads in a resource file:
/*
** get_global_resources - update $RSRC[]
**
** This is intended for resource files that
** do not change from one language or theme to another.
** One example is SQL statements
*/
function get_global_resources(&$RSRC, $context,
$VALS = array())
{
// $VALS is an associative array, it allows us to
// expand vars of the form: $VAL['foo'] within the
// resource file..
include "/usr/local/php-project/include/global/$context";
}
It's a pretty short function. I can optionally pass in an associative
array, $VALS, for use in expanding variables within
resources. This is what a call to get_global_resources()
looks like:
$this->get_global_resources($RSRC, "d-col.res", $VALS);
This is the sample resource file (d-col.res) itself:
<?php
$RSRC['SQL_HEAD_QUERY'] =<<<EOD
SELECT collection.title AS title,
collection.description AS description,
collection.comments AS comments,
collection.collection_dir AS collection_dir
FROM collection
WHERE
collection.collection_id = {$VALS['collection']};
EOD;
$RSRC['SQL_BODY_QUERY'] =<<<EOD
SELECT photo.photo_id AS photo_id,
photo.keywords AS keywords,
photo.caption AS caption,
photo.file_type AS file_type
FROM collection LEFT JOIN photo
ON photo.collection_id = collection.collection_id
WHERE
collection.collection_id = {$VALS['collection']}
GROUP BY photo.photo_id;
EOD;
?>
Some quick notes:
- Just like any other include file, you do not want to have any extra
characters after the closing
?>
$VALS is used to expand variables within a given resource.
This affects the timing of when you include your resource file, as you cannot
expand a variable which has not yet been defined. Sometimes you must break one
resource file into smaller chunks to address this.
What Do The Included Resources Look Like?
Now that we're pulling in things from resource files, it's helpful to
check on the $RSRC variable. I use the Apache web server and
like to scan the logs with tail -f logs/error_log to see
what's happening. Rather than cluttering up the browser side with a lot
of diagnostic output, I use:
function p_dbg($an_array, $array_info = "(no info given)")
{
static $dbg_count = 0;
ob_start();
$dbg_count++;
print "[" . $dbg_count . "] $array_info\n";
print_r($an_array);
$the_str = ob_get_contents();
ob_end_clean();
error_log("in p_dbg: ");
error_log($the_str);
}
Then I check on my resources via a debugging call:
$this->p_dbg($RSRC, "photo collection RSRC");