Customizing the Document with Joomla! 1.5: Part 1

Exclusive offer: get 50% off this eBook here
Joomla! 1.5 Development Cookbook

Joomla! 1.5 Development Cookbook — Save 50%

Solve real world Joomla! 1.5 development problems with over 130 simple but incredibly useful recipes

$26.99    $13.50
by James Kennard | September 2009 | Cookbooks Joomla! MySQL Content Management Open Source PHP

This two-part article by James Kennard shows how we can modify the server response by working with the global document object.

It contains the following recipes:

  • Setting the document title
  • Setting the document generator
  • Setting the document description
  • Adding metadata to the document
  • Changing the document character set
  • Changing the document MIME type
  • Controlling client caching of responses

Introduction

The classes that extend JDocument are intended for different response formats. The following table describes the classes and their purposes:

Class

Format

Default MIME type

Purpose

JDocumentError

error

text/html

Display a fatal error

JDocumentFeed

feed

application/rss+xml

 

or application/atom+xml

Syndication feed, RSS, or Atom

JDocumentHTML

html

text/html

Default document used for all typical Joomla! responses

JDocumentPDF

pdf

application/pdf

Adobe PDF representation

JDocumentRAW

raw*

text/html

All other circumstances

 

So what exactly does the format column represent? When a request is made, Joomla! uses the value of the request variable format to determine which document type to use. We really see this only when we retrieve something other than an HTML document, because this always defaults to html. For example, when we request an article as a PDF, we use a URI similar to this:

http://example.org/index.php?option=com_content&view=article&id=5&
format=pdf

The JDocumentError class is slightly different from the others. We should never really need to interact directly with this. We can, of course, invoke this document indirectly by raising a fatal error. For more information, refer to Error handling and reporting.

The Joomla! document object and views in Joomla! MVC components are closely related. For each format that we provide a view, we create a new JView subclass. For example, when we examine the content component, we can see that the article view supports HTML and PDF simply by the presence of the view.html.php and view.pdf.php files.

This article also deals with the static JResponse class. This class is used to define the HTTP response, including the HTTP headers.

The separation between JResponse and the JDocument object is not always as clear as one would hope. However, this is somewhat inevitable because the two are inextricably linked—the response describes and includes the document output. For example, outputting an HTML response will require the response Content-Type header field to be set accordingly, that is, as text/html.

Setting the document title

This recipe explains how to set the title of the current document. The exact meaning of title will depend on the type of document. For example, in an HTML document, this is the value encapsulated in the <head> tag.

Getting ready

Before we do anything, we need the global document object.

$document =& JFactory::getDocument();

How to do it...

To set the title of the document, we use the JDocument::setTitle() method

$document->setTitle('My Unique Title');

If we are outputting an HTML document, this should generate something like this:

<title>My Unique Title</title>

There's more...

Menu items can also define page titles. Thus, the actual title we use should not necessarily be the title of whatever we are viewing. To deal with this, we should use something along these lines:

// get the component and page parameters
$application =& JFactory::getApplication();
$params =& $application->getParams();
// get the page title
$pageTitle = $params->get('page_title', $defaultTitle);
// set the document title
$document->setTitle($pageTitle);

Setting the document generator

This recipe explains how to set the name of the piece of software that generated the page. The exact meaning of generator will depend on the type of document. For example, in an HTML document, this value is used in a tag.

Getting ready

Before we do anything, we need the global document object.

$document =& JFactory::getDocument();
Joomla! 1.5 Development Cookbook Solve real world Joomla! 1.5 development problems with over 130 simple but incredibly useful recipes
Published: September 2009
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

How to do it...

To set the generator, we use the JDocument::setGenerator() method . Remember that in HTML the value of generator is designed to identify the piece of software used to generate the page, not the author. For more information, refer to http://www.w3.org/html/wg/markup-spec/#meta.namet.

// set the generator
$document->setGenerator('My Component');

If we are outputting an HTML document, this should generate something like this:


<meta name="generator" content="My Component" />

See also

To learn more about adding metadata to the document, see the next but one recipe, Adding metadata to the document

Setting the document description

This recipe explains how to set the document description. The exact meaning of description will depend on the type of document. For example, in an HTML document, this value is used in a <meta> tag.

Getting ready

Before we do anything, we need the global document object.

$document =& JFactory::getDocument();

How to do it...

To set the description, we use the JDocument::setDescription() method. The description value is used by applications such as search engines to help determine the content of a page.

// set the description
$document->setDescription("A Joomla! 1.5 recipe");

If we are outputting an HTML document, this will generate something like this:


<meta name="description" content="A Joomla! 1.5 recipe" />

See also

To learn more about adding metadata to the document, refer to the next recipe, Adding metadata to the document.

Adding metadata to the document

This recipe explains how to add metadata to the document. The exact meaning of metadata will depend on the type of document. For example, in an HTML document, this is used to generate <meta> tags.

Getting ready

Before we do anything, we need the global document object.

$document =& JFactory::getDocument();

How to do it...

To add metadata to the document, we use the JDocument::setMetaData() method. For example, to set the value of the keywords metadata, we would do the following:

// set the keywords metadata
$document->setMetaData('keywords', 'Joomla! Cookbook');

If we are outputting an HTML document, this will generate something like this:

<meta name="keywords" content="Joomla! Cookbook" />

If we want to add an http-equiv <meta> tag, we must provide the third parameter with the $http_equiv Boolean value. For example, to add the http-equiv metadata Expires, we would do the following:

// set the expiry date
$expiresDate = 'Mon, 23 Mar 2009 15:48:00 GMT';
$document->setMetaData('Expires', $expiresDate, true);

If we are outputting an HTML document, this will generate something like this:

<meta http-equiv="Expires"
content="Mon, 23 Mar 2009 15:48:00 GMT" />

See also

To set description and generator metadata, we do not use the JDocument::setMetaData() method. For more information, refer to the previous two recipes, Setting the document description and Setting the document generator.

Changing the document character set

This recipe explains how to change the document character set. By default, the character set is UTF-8, a multibyte Unicode character encoding.

Getting ready

Before we do anything, we need the global document object.


$document =& JFactory::getDocument();

How to do it...

To change the document character set, we use the JDocument::setCharset() method. For example, this will set the character set to US-ASCII:


// set the character set
$document->setCharset('us-ascii');

How it works...

The character set defines the way in which the characters are encoded in the response data. For most document types, for example HTML, the document can only have one encoding. Composite document types, such as multipart/alternative, may use several encodings. In these instances—relatively rare, at least for Joomla!-it is necessary to micromanage the character encoding of each part.

The character encoding is passed as part of the HTTP response headers. The following example shows a set of HTTP headers where the character set has been changed to US-ASCII:

Field

Value

Date

Mon, 23 Mar 2009 10:26:26 GMT

Server

Apache/2.2.8 (Win32) PHP/5.2.6

Expires

Mon, 1 Jan 2001 00:00:00 GMT

Last-Modified

Mon, 23 Mar 2009 10:26:26 GMT

Content-Type

text/html; charset=us-ascii

 

Joomla! 1.5 Development Cookbook Solve real world Joomla! 1.5 development problems with over 130 simple but incredibly useful recipes
Published: September 2009
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

Setting the character set in a document doesn't necessarily guarantee that the defined character set is used by the client. For example, in an HTML document it is possible to override the encoding defined in the response headers using an http-equiv <meta> tag.

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

The next recipe, Changing the document MIME type, explains how to modify the HTTP header Content-Type. Or put simply, it shows how to change what the document represents; for example, a JPEG image.

Changing the document MIME type

This recipe explains how to change the MIME (Multipurpose Internet Mail Extensions) type of the document. Changing this enables us to inform the client what the data we are sending represents. In Joomla!, we generally only use this when we have invoked the RAW document.

Getting ready

Before we do anything, we need the global document object.

$document =& JFactory::getDocument();

How to do it...

To modify the document MIME type, we use the JDocument::setMimeEncoding() method.

$document->setMimeEncoding('text/plain');

Note that the MIME type we provide is just the MIME type and nothing else. For example, "text/html; charset=utf-8" is not valid because it also includes the Content-Type parameter charset.

How it works...

The MIME type is used to define the way in which the data being transferred has been encoded, for example image/jpeg. This, in turn, tells the client how to handle the response. For example, the headers of an HTTP response might look like this:

Field

Value

Date

Mon, 23 Mar 2009 10:26:26 GMT

Server

Apache/2.2.8 (Win32) PHP/5.2.6

Expires

Mon, 1 Jan 2001 00:00:00 GMT

Last-Modified

Mon, 23 Mar 2009 10:26:26 GMT

Content-Type

image/jpeg; charset=utf-8

 

 

So when would we want to change the MIME type? A good example is when we have used the database to store binary data. For example, it is not uncommon to use a database to store thumbnails. To serve a thumbnail, we would need to output the raw binary data and change the MIME type to suit the image format. For more information, refer to the Outputting a RAW document from a component recipe later in this article.

See also

For information about changing the value of the Content-Type parameter charset, refer to the previous recipe, Changing the document character set.

Controlling client caching of responses

This recipe explains how to control client caching of responses. By default, Joomla! always assumes that caching by clients should not be allowed. However, in instances where we are dealing specifically with data we know will not change, or will only change occasionally, allowing a client to cache a response can be beneficial, as it could significantly reduce the load on the server. Note that client caching is completely separate from Joomla!'s own cache.

How to do it...

To allow clients to cache responses, we use the static JResponse::allowCache() method.

// allow clients to cache the response
JResponse::allowCache(true);

How it works...

The HTTP 1.1 protocol (http://www.ietf.org/rfc/rfc2616.txt) defines caching as:

A program's local store of response messages and the subsystem that controls its message storage, retrieval, and deletion. A cache stores cacheable responses in order to reduce the response time and network bandwidth consumption on future, equivalent requests. Any client or server may include a cache, though a cache cannot be used by a server that is acting as a tunnel.

When we allow client caching in Joomla!, it explicitly defines an expiration time using the HTTP Expires header field. This is always calculated based on the current time plus 900 seconds (15 minutes).

Unfortunately, it is not generally possible to change the expiry time. For a potential work-around, refer to the last recipe in this article, Using a custom JDocument in a component (PHP 5 only), and consider overriding the JDocument::render() method.

However, there is a way in which we can define an overriding expiry time. The Cache-Control header fi eld was added in HTTP 1.1 and is recognized by the majority of clients. We can provide a maximum age that a cache should allow a cached entity to reach. And what's good about this is that it overrides the Expires header field.

To add this to the response, we use the JResponse::setHeader() method. The following example sets the maximum age to 1800 seconds (30 minutes).

// set the maximum age in seconds
JResponse::setHeader('Cache-Control', 'max-age=1800');

There's more...

It is a good practice to inform the document when the response was last updated. This is achieved using the JDocument::setModifiedDate() method. This method accepts one parameter, the modified date.

// get the document object
$document =& JFactory::getDocument();
// set the modified date
$document->setModifiedDate('Mon, 23 Mar 2009 12:07:31 GMT');

The date must be provided as a string in the HTTP-date format, as defined in RFC 2616 section 3.3.1. This method does not accept JDate objects. However, we can use the JDate::toRFC822() method to generate a suitable date string.

// get JDate object that represents the current date and time
$jdateObject =& JFactory::getDate();
// set the modified date using the JDate object
$document->setModifiedDate($jdateObject->toRFC822());

The modified date is used directly to set the Last-Modified header field. This field is used primarily for caching purposes. To quote RFC 2616:

The Last-Modified entity-header field value is often used as a cache validator. In simple terms, a cache entry is considered to be valid if the entity has not been modified since the Last-Modified value.

>> Continue Reading Customizing the Document with Joomla! 1.5: Part 2

[ 1 | 2 ]

If you have read this article you may be interested to view :

About the Author :


James Kennard

James Kennard is a computer programmer. He has worked with various PHP and MySQL applications, since 2002. He quickly discovered Mambo/Joomla! because of its flexible extension manager. James currently maintains one open-source Joomla! component, which has been translated into over fifteen languages. Moreover, he has plans to build two more open-source components. Examples of his work can be found on his personal website www.webamoeba.co.uk.

Books From Packt

Symfony 1.3 web application development
Symfony 1.3 web application development

Zend Framework 1.8 Web Application Development
Zend Framework 1.8 Web Application Development

Papervision3D Essentials
Papervision3D Essentials

Joomla! 1.5 SEO
Joomla! 1.5 SEO

Joomla! 1.5x Customization: Make Your Site Adapt to Your Needs
Joomla! 1.5x Customization: Make Your Site Adapt to Your Needs

Pentaho Reporting 3.5 for Java Developers
Pentaho Reporting 3.5 for Java Developers

Drupal 6 Site Blueprints
Drupal 6 Site Blueprints

Ext JS 3.0 Cookbook
Ext JS 3.0 Cookbook

 

 

Your rating: None Average: 3 (1 vote)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
m
2
p
s
r
r
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software