Learning Drupal 6 Module Development - Butcher Matt - E-Book

Learning Drupal 6 Module Development E-Book

Butcher Matt

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

In Detail



With great power comes... tremendous flexibility. Drupal is an award-winning open-source Content Management System, and the feature-packed sixth release is right around the corner. It's a modular system, with an elegant hook-based architecture, and great code. These are a few of the perks that make Drupal a choice platform for developers who want the power of an established CMS, but the freedom to make it work for them. From social networking to AJAX to e-commerce, the hundreds of existing modules attest to Drupal's flexibility. When you create a new module for Drupal, it fits seamlessly into the look and feel of your overall site. If you can think it in PHP, you can code it as a Drupal module.



Dive into Drupal module development as we create the Philosopher Biographies website, developing new modules and themes to meet practical goals. Create custom content types. Add AJAX functionality with the jQuery library. Use external XML APIs to add content to your site. Email newsletters to site members. Use themes. Empower administrators with extra features. And bundle it all up in a custom installation profile. You won't find a "hello world" here!



If you're eager to start creating modules for Drupal 6, this is your book. Walk through the development of complete Drupal modules with this primer for PHP programmers. Specifically written for Drupal 6, this book will get you coding modules as quickly as possible, and help you add the features that will give your work that professional gloss!



Just getting started with Drupal development? This book will give you a clear, concise and, of course, practical guidance to take you from the basics of creating your first module to developing the skills to make you a Drupal developer to be reckoned with.



Are you a Drupal developer looking to update to version 6? This book covers the new and updated APIs to guide your transition to Drupal 6. The new menu system, the Forms and Schema APIs, and many core revisions are covered in this book.



Walk through the development of complete Drupal 6 modules with this primer for PHP programmers, written specifically for Drupal 6 to get you started coding your first module.



Are you a Drupal developer looking to update to version 6? This book covers the new and updated APIs to guide your transition to Drupal 6. The new menu system, the Forms and Schema APIs, and many core revisions are covered in this book.



 

Who this book is for



This book is written for PHP developers who want to add custom features to Drupal. You will need to know the basics of PHP and MySQL programming, but no experience of programming Drupal is required, although you will be expected to be familiar with the basic operation of Drupal.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 409

Veröffentlichungsjahr: 2008

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Learning Drupal 6 Module Development
Credits
About the Author
About the Reviewers
Preface
What This Book Covers
Who Is This Book For?
Conventions
Reader Feedback
Customer Support
Downloading the Example Code for the Book
Errata
Questions
1. Introduction to Drupal Modules
Drupal's Architecture
Module Architecture
Core Modules
Hooks
Themes
Crucial Drupal Concepts
Nodes
Comments Are Not Nodes
Users
Access and Security
Blocks and Page Rendering
Menus
Forms
Database and Schema APIs
Developers' Tools
Developer Module
Coder Module
A Word on Our Demonstration Site
Summary
2. Creating Our First Module
Starting Out
A Place for the Module
Creating a .info File
A Basic .module File
Our Goal: A Block Hook
Starting the .module
The hook_block() Implementation
The t() Function
A view Operation
Installing a Module
Step 1: Copying the Module
Step 2: Enabling the Module
Step 3: Displaying the Module's Content
Using Goodreads Data
Modifying the Block Hook
Retrieving XML Content over HTTP
The watchdog() Function
Processing the HTTP Results
Formatting the Block's Contents
Finishing Touches: hook_help()
Summary
3. The Theme System
The Theme System's Architecture
Theme Templates
Theme Engines
Theme Hooks
Creating a Custom Theme
Organization of Themes
Sub-themes (Derivative Themes)
How Each Theme Functions
Creating a Theme
Creating the Theme Directory
A .info File
A CSS Stylesheet
A PHPTemplate Theme
Template Structure
A Page Template for Descartes
Using PHP to Override Theme Behavior
Custom Breadcrumbs
Interacting with Other Theme Functions
template.php Gotchas
Creating a Screenshot
From Here to a Full Theme
Summary
4. Theming Modules
Our Target Module: What We Want
Creating a Custom Content Type
Using the Administration Interface to Create a Content Type
Content and Nodes
The Foundations of the Module
A Simple Database Lookup
Getting the Node ID
Getting the Node's Content
Theming Inside a Module
Registering a Theme
Creating a Theme Hook Function
Adding a Stylesheet
Overriding the Default Theme from a Theme
A Quick Clarification
Overriding the Default Theme's CSS
Overriding Layout with Templates
Summary
5. Using JavaScript and AJAX/JSON in Modules
Picking up Where We Left Off
Introducing jQuery
Modifying HTML with jQuery
Checking for JavaScript Support with Drupal
Namespaces in JavaScript
Drupal's Namespace
A Drupal Function: Drupal.jsEnabled()
Delaying JavaScript Execution with jQuery
Including JavaScript from the Module's Theme
Writing a Drupal AJAX/JSON Service
The JSON Format
Our Module Roadmap
Server Side: Defining a New Page
Creating a JSON Message
Mapping a Function to a URL
Passing PHP Settings to JavaScript
Client Side: AJAX Handlers
A JavaScript Function to Get JSON Content
Adding an Event Handler
Summary
6. An Administration Module
The emailusers Module
The Beginning of the Module
Mail Configuration
Registering an Administration Page
A Detailed Look at the Path
Marking the Path as an Administration Page
Path Registration Parameters
Defining the Callback Function
Handling Forms with the Forms API (FAPI)
Loading a Form with drupal_get_form()
A Form Constructor
Handling Form Results
The Form Submissions Callback
Sending Mail with the Mail API
Formatting Mail with hook_mail()
Altering Messages with hook_mail_alter()
Altering Hooks
Adding a Mail Footer
Incorporating the Module into Administration
Modifying the User Profile with hook_user()
Constructing the Content
Summary
7. Building a Content Type
The biography Module
The Content Creation Kit
The Starting Point
The Module Installation Script
The Schema API: Defining Database Structures
A First Look at the Table Definition
Defining Fields (Columns)
Defining Keys and Indexes
Correlating the New Table with Nodes
The Content Creation Form
Overriding hook_form() Defaults
Adding New hook_form() Form Elements
Access Controls
Database Hooks
Database Inserts with hook_insert()
Updating and Deleting Database Records
Hooks for Getting Data
Loading a Node with hook_load()
Preparing the Node for Display with hook_view()
Theming Biography Content
Registering a Theme
The biography_info.tpl.php Template
The Results
Summary
8. Filters, Actions, and Hooks
The sitenews Module
Getting Started
Citing Dependencies in the .info File
The Beginning of the .module File
A Simple Content Type, Defined in Code
Creating Filters and an Input Format
Creating Filters
The First Filter: News Brief Placeholders
The Second Filter: Remove All Tags
Adding an Input Format
The Beginning of an Action
Implementing hook_action_info()
The Action Callback
Defining a Hook
Invoking a Custom Hook
So What Is a Hook?
Creating a hook_sitenews() Function
Implementing hook_sitenews() in Other Modules
In the philquotes Module
In the biography Module
Theming Content before Returning It
Completing the Action: Theming and Mailing
Theme Functions
The hook_mail() Implementation
Adding a Trigger
Summary
9. An Installation Profile
Introducing Installation Profiles
Why Use Installation Profiles?
Setting up a Distribution
Creating a Profile Directory
Programming Profiles
The .profile Script
The Details Function
The Modules List
The Installation Task System
The Profile Task
A Basic Profile Task
A Complex Profile Task
Creating a Content Type
Creating a Trigger
Moving to the Next Task
The 'profile' Task is Special
Registering a New Task
The Theme Selection Form
Returning to the philosopherbios_pick_theme Task
The Submission Handler
Finishing the Installation Profile
Packaging the Distribution
Summary
Index

Learning Drupal 6 Module Development

Matt Butcher

Learning Drupal 6 Module Development

Copyright © 2008 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: May 2008

Production Reference: 1020508

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-847194-44-2

www.packtpub.com

Cover Image by Cadym Guryevich (<[email protected]>)

Credits

Author

Matt Butcher

Reviewers

Jason Flatt

John Forsythe

Edward Peters

David Norman

Sherif

Senior Acquisition Editor

Douglas Paterson

Development Editor

Swapna V. Verlekar

Technical Editor

Akshara Aware

Editorial Team Leader

Mithil Kulkarni

Project Manager

Abhijeet Deobhakta

Project Coordinator

Patricia Weir

Indexer

Monica Ajmera

Proofreader

Chris Smith

Production Coordinator

Aparna Bhagat

Cover Work

Aparna Bhagat

About the Author

Matt Butcher is the principal consultant for Aleph-Null, Inc. (http://aleph-null.tv ), where he specializes in content management systems, Linux system integration, and Open Source technologies. He has been an active participant in open‑source technologies for over a decade. Along with Learning Drupal 6, Matt has also written Mastering OpenLDAP, Managing and Customizing OpenCms 6, and Building Websites with OpenCms, all of which are published by Packt. When not pushing bits, Matt likes to explore Colorado with his wife and three daughters.

The Drupal community has not only been a boundless source of information, but also a positive environment. This community is to be commended for creating a successful habitat for growing a top-quality application. Writing this book has involved a veritable army of editors, technical reviewers, and proofreaders. This book has benefi ted tremendously from their hard work. I would like to thank Douglas Patterson not only for being my editor, but for getting me involved with Drupal in the fi rst place. Thanks to Patricia Weir and Swapna V.Verlekar, who have worked tirelessly on the book. I owe a huge debt of gratitude to John Forsythe and Jason Flatt, whose meticulous reading and copious suggestions have had a profound infl uence on the fi nal state of this book. I'd also like to thank: Edward Peters, David Norman, and Sherif for their invaluable suggestions. Thanks also to the many individuals at Drupalcon 2008 who provided input and who took the time to chat with me about Drupal. Finally, thanks to Angie, Katherine, Claire, and Annabelle for putting up with a few late nights and some occasional whining.

About the Reviewers

Jason Flatt has been involved with the Drupal community since 2005. He has been involved in the computer industry professionally since 1992 and at the hobby level since 1978. He was heavily involved in the open-source Linux distribution Source Mage GNU/Linux from 2001 through 2005, where he got his introduction to Drupal in looking for a replacement CMS for its website.

Since 1995, Jason has been an owner or part owner in four different computer consulting companies. He currently owns his own computer consulting company and is in the process of developing a Drupal consulting and web application development company.

He has developed and maintains contributed modules on drupal.org. Jason's Drupal user account (oadaeh) can be found at http://drupal.org/user/4649.

I would like to thank my wife, Corrine, for giving me the time, freedom, and encouragement to pursue Drupal-related tasks, including reviewing this book.

John Forsythe is a programmer and web developer who's been building websites since 1997. In 2006, he left a full time job in tech support to concentrate on Drupal development. He currently runs a number of popular Drupal sites, including DrupalModules.com, a community-powered module rating and review service, and Blamcast.net, a web development blog.

John's Drupal account can be found at http://drupal.org/user/101901.

I would like to thank my parents for their continued support and encouragement.

Edward Peters has worked all his adult life with Initiatives of Change (IofC), an international trust-building network (www.iofc.org). Since 2002 he has managed IofC's global Internet operation, servicing the needs of activists in many countries and languages. He is currently overseeing the move of the organization's proprietary CMS into Drupal. He also does freelance web development work for a number of small clients (www.edwardpeters.co.uk).

Preface

Drupal is a highly successful open-source Content Management System (CMS). It is well‑respected for its robustness, its flexible and immaculate code, and its seemingly infinite capacity for extension and customization.

Drupal 6, released early in 2008, represents a significant evolution in this already mature CMS. In this book, we build extensions for Drupal 6, focusing on the important APIs and libraries. We also highlight the new features introduced in version 6, making this book appropriate not only for those new to Drupal, but also those who are transitioning from version 5.

This book provides a practical, hands-on approach to developing Drupal modules. We also take a developer-centered look at themes and installation profiles—two other facets of Drupal that the developer should be familiar with. Each chapter focuses on the creation of a custom extension. Using this approach we develop a handful of modules, a theme, and an installation profile. However, more importantly, we get a practical perspective on how to make the most of Drupal.

By the end of the book, you will have a solid understanding of how to build modules for Drupal. With the knowledge of foundational APIs and libraries, you will be able to develop production‑quality code that fully exploits the power and potential of Drupal 6.

What This Book Covers

This book focuses on developing modules for Drupal 6. Each chapter introduces new concepts, libraries and APIs, while building on material from previous chapters.

Chapter 1 is a developer's introduction to Drupal. We take a look at Drupal's architecture, focusing on modules and themes. After covering some of the important concepts and taking a high-level look at foundational APIs and libraries, we finish up with a look at some useful development tools.

Chapter 2 gets us working on our first module. In this chapter, we develop a Drupal module that takes data from an XML feed and displays it as a block on our Drupal site. In this chapter, you will learn about the basics of module development, including what files need to be created and where they go. Hooks, a major component of Drupal development, are also introduced here.

Chapter 3 switches gears from modules to themes. Learning the theming system is integral to being able to produce high-quality modules. In this chapter, we create a theme using CSS, HTML, and PHPTemplates. We also take a look at the theme system architecture, along with some of the APIs.

Chapter 4 builds on the introduction to theming. In this chapter, we develop a new module that deals with a custom content type, a quote. This module uses the theming subsystem to prepare quotes for display. Our focus here is using the theme system to enrich modules. The theme API covered in this chapter is used throughout the rest of the book.

Chapter 5 focuses on Drupal's JavaScript libraries. Starting with the module we built in Chapter 4, we use the jQuery library and a couple of Drupal hooks to implement an AJAX (Asynchronous JavaScript and XML) service. This chapter also introduces the Database API and the menu system.

Chapter 6 is focused on building an administration module. This module provides an interface for administrators to send email messages to users. However, the Mail API is not the only thing we will look at. The tremendously important Forms API is also introduced here. We also get our first look at Drupal's access control features.

Chapter 7 takes a closer look at Drupal nodes. In this chapter, we use the Schema API, the Database API, and the node system to build a content type that represents a biography. Module installation files are introduced, and the Forms API and access control mechanisms are revisited.

Chapter 8 discusses filters, actions, and hooks—three of the more advanced features of Drupal. We create a module for emailing a newsletter to our users. We implement filters to prepare content for the email message. Actions and triggers are used to automatically send our newsletter when it is ready. Also, to allow other modules to interact with this one, we define our own custom hook that other modules can implement.

Chapter 9 changes tracks, focusing on installation profiles. In this chapter, we build an installation profile that can install a custom version of Drupal preloaded with the modules and themes of our choice. Working with the installer, we get a glimpse into Drupal's inner workings. Along with learning how to write code in this minimalistic pre-installation environment, we also look at registering themes and defining triggers automatically.

Who Is This Book For?

This book is written for PHP developers who want to add custom features to Drupal. You will need to know the basics of PHP and MySQL programming, but no experience of programming Drupal is required, although you will be expected to be familiar with the basic operation of Drupal.

Reader Feedback

Feedback from our readers is always welcome. Let us know what you think about this book, what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply drop an email to <[email protected]>, making sure to mention the book title in the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer Support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the Example Code for the Book

Visit http://www.packtpub.com/files/code/4442_Code.zip to directly download the example code.

The downloadable files contain instructions on how to use them.

Errata

Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing this you can save other readers from frustration, and help to improve subsequent versions of this book. If you find any errata, report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to the list of existing errata. The existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Questions

You can contact us at <[email protected]> if you are having a problem with some aspect of the book, and we will do our best to address it.

Chapter 1. Introduction to Drupal Modules

Drupal (pronounced Droo-puhl) is a web-based Content Management System (CMS). Like many other CMS frameworks, Drupal provides a modular interface, so that developers can customize and extend the CMS system. However, one thing that distinguishes Drupal from other web CMS platforms is the power and flexibility of its modular system.

This module system is the main focus of the book. In this chapter, we will take an introductory look at Drupal modules, and how they fit within the Drupal framework. Specifically, we will look at the following:

The Drupal structureAn introduction to modules and themesA developer's overview of important Drupal concepts and APIs such as nodes, menus, and formsUsing tools for module development

Drupal's Architecture

In one sentence, Drupal is a web-based content management system written in PHP that uses a relational database (usually MySQL) for storage.

PHP, which stands for PHP Hypertext Processor, is a high-level language designed for developing web applications. PHP offers a flexibility that supports both procedural and object-oriented (OO) approaches to software development.

The Drupal core is meticulously written in procedural-style PHP. Code follows strict conventions and every file and function is documented in the source code. APIs are often minimalistic, kept brief and functional. These factors make Drupal's source code easier to read in many regards than run-of-the-mill PHP code. However, the minimalism of the code can be deceptive too; the simple tools and modules are combined to produce the surprisingly complex features of this robust content management system.

Note

Why isn't Drupal object-oriented?

This question is asked often. The answer has several facets, one of which is simply that when the project began, PHP still wasn't up to snuff on the OO side. However, looking beyond the absence of constructors and classes, it turns out that Drupal employs many of the OO principles: encapsulation, inheritance, polymorphism, etc. The OO programmer will quickly feel at home with Drupal's architecture.

A simplified stack diagram of Drupal looks something like the following:

At the center of Drupal is a core set of files consisting of bootstrapping code and important oft-used libraries. The Drupal Core Libraries act as the glue layer to bind Drupal's modules. They provide services such as database connectivity and management (illustrated by the dashed line to the database above), as well as the highly customizable hook framework about which we will talk throughout this book. Other standard features such as mail and image library abstractions, internationalization, and Unicode support are also included as Drupal Core Libraries.

Note

Many of the required system modules are referred to as Drupal Core Modules. In the above diagram, I would include these along with the rest of the modules, as they are modules in all proper respects.

But as important as these files are, there is a reason why the Drupal Core Libraries section in the above diagram is comparatively small. While these libraries provide a potent feature set, the real power in Drupal comes from its modular architecture.

Module Architecture

What exactly is a module and what is its purpose?

The second question is easier to answer: Drupal's module mechanism is designed to provide a uniform method of extending Drupal's capabilities. The purpose of a module is to extend Drupal's capabilities. This answer brings us much closer to answering the first question. A module is a bundle of PHP code and supporting files that use Drupal's APIs and architecture to integrate new functional components into the Drupal framework.

The purpose of this book, then, is to explain how to write these bundles of code. The above definition means we will need to get familiar with the Drupal framework and its APIs. That is precisely what we will be doing as we progress through the book. Let's start here by taking a glance at the module architecture.

The files that make up modules are grouped into specific locations under Drupal's directory structure. That is, in the Drupal installation on a server's file system, Drupal modules must reside in a few specific locations (we will look at these in the next chapter).

When Drupal needs information about its modules, it will look in these predetermined locations. Each module is contained in its own directory, and has at least two files—one describing the module's content and one or more files containing code and other supporting material. (We will create both these files when we build our first module in the next chapter.)

Before a module can be used, it must be enabled by a Drupal administrator. However, once a module is enabled, then it is loaded as required, and Drupal passes requests to the module as necessary.

Core Modules

Some modules are so important that removing them would disable features essential for Drupal's operation. Likewise, there are some modules that provide features needed by a wide variety of systems. These two batches of modules, both of which are maintained by the Drupal development team, are collectively referred to as the Drupal Core Modules. These modules are included by default in the Drupal distribution, and enjoy active maintenance and development by the Drupal community.

Besides their prominent role in Drupal's operation, there is little to architecturally distinguish the Drupal Core Modules from any other module. They follow the same guidelines and use the same APIs. There is nothing particularly arcane about these modules.

Note

From Drupal's administration section, you can look at the list of core modules in Administer| Site building | Modules. The most important modules are the five that are required: Block, Filter, Node, System, and User. These cannot be uninstalled or disabled. Others, such as Menu, Locale, and Taxonomy provide basic services that are needed even in basic installations.

One of the diamonds in Drupal's architectural crown is the ease with which various modules can interact. Using the hook architecture, the services that modules provide can be woven together to create robust features without copious amounts of code.

In the course of this book, we will often make use of APIs and facilities provided by Drupal Core Modules. However, don't expect any chapters to walk through existing Drupal code. We make use of these modules, but we won't dwell closely on the implementation details of specific core modules. In this book, we will focus on writing our own modules.

That said, the core modules do provide an excellent reference for how Drupal code should be written. You may find it beneficial to read through some of that code in conjunction with this book.

Hooks

How does Drupal know when to invoke a module to handle a particular request?

This is done through Drupal's hook mechanism, which we will examine carefully in this book. To start out, here is a brief explanation of how hooks work.

When Drupal handles a request from a user, it proceeds through a series of steps. For example, the Drupal core first bootstraps the application, defining critical variables and oft-used functions. Next, it loads critical libraries, themes, and modules. Next, it continues processing the request, mapping the requested URI to the correct handling code, and so on. Later, it applies a theme to the data, formatting information for output. Finally, it returns this output to the user's browser.

At predefined moments in this step-by-step process, Drupal executes hooks. What does this mean? In short, it means that Drupal examines some or all of the currently enabled modules, looking for functions that follow specific, predefined patterns. Some have linked this process to the "callback" method often used in event handling models. It is similar to this, but more dynamic.

For example, while it is creating the content for a page view, Drupal might scan modules for functions named <modulename>_block() and <modulename>_view() (where <modulename> is replaced by the name of each module that it checks). Modules that contain such functions are said to implement the hook_block() and hook_view() hooks.

When Drupal finds such functions, it executes them, and uses the data these functions return to build a response to send to the user. Drupal then continues its step-by-step processing of the request, perhaps executing many other hooks as it goes.

Once all the steps have been completed and a response sent to the user, Drupal cleans itself up and exits.

Note

Hooks for Object-Oriented Programmers

Those familiar with object-oriented (OO) programming may find it helpful to think of a hook as a mechanism similar to interface methods (or abstract methods) in OO languages. Hooks are functions that Drupal will look for, and in certain cases, expect in your module. Like interface methods, a hook's function signature must match Drupal's expected signature. Unlike interfaces, however, the module developer can choose (to a certain degree) which hooks to implement, and which to ignore. Drupal does not require that every defined hook be implemented.

Modules can define their own hooks, which other modules can then use. In this way, the hook mechanism can be extended to provide complex customized behavior.

When a module provides a function that matches a hook's signature, we say that that module implements that hook. For example, imagine that Drupal has a hook called hook_example(). If we were to define a module called mymodule that contained a function called mymodule_example(), we would be implementing hook_example().

We will write our first hook implementation in the next chapter.

Themes

Processing power isn't everything, especially for a web-based CMS system. A commercial-grade CMS must make it possible for site designers to give the site the look and feel they desire. Drupal provides a robust theme system for just this purpose.

The Drupal theme system is surprisingly complex. Just as with modules, the system is designed to allow extension and improvement and the hook mechanism is employed to allow this sort of extension.

While the code under the hood boasts a large (and complex) API, the top layer is surprisingly uncomplicated, and revolves around the idea of a theme.

A theme is a bundle of resources, including PHP templates, CSS, JavaScript, and images, that provides layout and style information for some or all of the Drupal content.

At its simplest, a theme may be composed of only a handful of files—a stylesheet, an information file, and a couple of images. In fact, using existing Drupal styles, one can create a custom theme in no time.

But themes can grow to meet the needs of the implementer. Custom templates, usually written in the PHP template language, can specify the details of the HTML structure. Special PHP files can be written to override theme engine behaviors. Complex configurations of JavaScript and CSS files are supported as well. Even modules can be used to interact with the theming system.

In short, a theme can be as simple or complex as the implementer desires.

Chapter 3 is devoted to themes, and in that chapter we will first create a simple theme, and then build up to a moderately complex theme.

Themes and modules are critical components in the Drupal architecture, and obviously the main focus of this book. However, before moving on, let's look at Drupal from another angle. Let's briefly examine how Drupal handles content.

Crucial Drupal Concepts

Note

This book is geared toward developers, and to keep the book manageable, some introductory material must be glossed or skipped.

For a thorough introduction to Drupal 6, I recommend David Mercer's book Building Powerful and Robust Websites with Drupal 6, also published by Packt Publishing.

Throughout the book, it is assumed that the reader has a moderate amount of Drupal experience, and is comfortable administering a Drupal site.

However, there are some particular facets of Drupal that deserve an introduction. We will look at some of the aspects in this book. Others are common Drupal terms that take on additional shades of meaning when examined from a developer's perspective.

In this section, we will focus on Drupal concepts that will be crucial in this book. We will start out with one of the biggest topics: nodes.

Nodes

Drupal is a content management framework. When we think of content in this context, we typically think about text objects like news articles or blog entries.

This concept of a generic text-based piece of content is captured in Drupal with the term Node. A node, in Drupal parlance, is a generic object for representing textual content.

Note

While nodes are designed to be text-based, some of the contributed multimedia modules extend the node system to handle content that is not text-centric, such as images or audio files.

Nodes are stored in the database and retrieved as needed. Among other things, all nodes have:

A unique Node ID (nid)At least one Version ID (vid) used to track revisionsCreation and modification dates, as well as identifying information for the user who worked on the nodeMetadata such as publishing state (status), language of the node (and translations), and so on

In addition to these, most nodes also have a title and a body (contents). (Administrators and developers may choose to turn off a title or body, though the database always has a place for these.)

Nodes are used to back many different kinds of text content in Drupal. To understand this, let's look briefly at the process of creating new content.

By default, creating new content in Drupal is done by clicking on the Create content link in the main navigation. On this page, the user is prompted to select the content type for their new page:

The above screenshot shows three different available content types.

The Story and Page content types are included by default. The Quotes content type is one we will create in this book.

Note

In Chapter 4, we will create the Quotes content type. In Chapter 7, we will extend the node object to create an even more elaborate content type representing a biography.

In fact, all the three content types are text-based and each of them is implemented using nodes. For practical purposes, the node is the heart of Drupal's content management system.

In this book we will deal with nodes many times, and we will take a close look at the node API.

Comments Are Not Nodes

While most article-like content is based on the node, one major text component stands out as an exception—the comment. A comment is usually implemented as a user-level feedback mechanism attached to stories, pages, blog entries, and similar articles. When you create a new page, for example, you have the opportunity to allow or disallow user comments. If comments are enabled in read/write mode, users will be able to comment on articles.

Following is an example comment-posting screen:

Comments serve a different role than nodes. For example, a comment is always linked to a node.

While comments will not play a big role in this book, they illustrate a point: Drupal is a very flexible architecture, and can accommodate extensions (like comments) that do not fit "the pattern" of typical text content and do not make use of the node API.

Note

Since comments are, in many ways, very node-like, there is discussion among Drupal developers of transitioning comments into the node framework in Drupal 7.

While it is possible to implement a new form of content by creating a library that does not make use of nodes, it is often more efficient to build on the existing (well-tested, robust) node API.

Users

Another important type of object in Drupal is the user. User records are maintained using this object type. Just as with comments and nodes, user data is stored in the database, and drawn out during processing.

Information about a user is used for purposes such as authentication, determining preferences and permissions, and logging.

In the course of this book, we will make use of the user APIs to perform permissions checks, get contact information, and discover user preferences.

Access and Security

Permissions are closely linked to the user object. Drupal provides a role-based mechanism for granting permissions to collections of users. In a nutshell, a user belongs to a role, and permissions are granted to (or revoked from) a role.

Thus, when checking access to a resource, Drupal loads a user object, finds the user's roles, and then finds the roles' permissions.

Does this sound like a lot of work? Well, it's not work the module developer must do. Drupal provides functions for performing permissions checks. Most of the time, module code does not need to directly discover a user's role before determining permissions. The users API does that work for us.

Blocks and Page Rendering

The term block is equally important. While a node is used to store and present articles and "larger" pieces of content, a block is used to present smaller bits of content. For example, navigational menus, daily quotes, polls, and search boxes are often presented using blocks.

A block is not a type of content. Actually, it is a unit of abstraction (a placeholder) used primarily to display other content. Administrators can use the Blocks editor to determine where blocks are displayed on a themed page:

The highlighted sections in the above screenshot show where blocks can be displayed.

From the developer's perspective, blocks are an important part of module creation. In fact, our very first module (which we will create in the next chapter) will display a block.

Defining a block in a module is a matter of selecting content to display, and then passing it on to the correct formatting tools.

In Chapters 3 and 4, we will look into themes, where we will format block content.

Menus

Closely related to blocks are menus. Drupal has a sophisticated menu system whose main purpose is the construction of navigation. For example, the above screenshot shows the main menu, with such items as Code review, My account, Create content, and so on. This menu is dynamically generated by the Drupal menu system.

But the Drupal menu system is a more sophisticated device than this simple description. It also functions as the primary tool for mapping URLs to specific handling routines. Using the menu API, developers can correlate paths with specially defined functions.

In Chapter 5, we will use the menu system to create a JSON (JavaScript Over the Network) service, and in Chapter 6 we will examine the more traditional way of mapping a path to a module.

Forms

The primary method of submitting content over the Web is through HTML forms. While the ubiquity of forms makes life easy for the web user, the dearth of good forms processing tools usually makes form development a joyless chore for programmers.

However, forms processing is one area in which Drupal excels. The Forms API (FAPI) provides a programming interface that takes the pain out of form development (or at least significantly reduces the pain).

Using the FAPI, developers can provide a single form definition and let Drupal build and display the form, collect the results, and even validate and escape form data. Drupal even provides forms caching and advanced AHAH (Asynchronous HTML And HTTP) features.

As Drupal development has progressed, the Forms API has got better and better, and the Drupal 6 version exhibits many improvements.

Chapter 6 is the first to explicitly cover the forms API, and it is used again in Chapter 7.

Database and Schema APIs

Beneath many of these higher-level frameworks and APIs is the layer responsible for managing and manipulating the database. Drupal provides a low-level database API to simplify the process of writing SQL queries.

This API provides some degree of security for database queries, and also makes it easier to write SQL that is portable across different databases.

Also the new Schema API, introduced in Drupal 6, makes it possible to define how a database should be structured without writing the actual SQL. Since different databases use different constructs for defining tables, this API simplifies the project of writing portable modules.

These APIs are discussed primarily in Chapter 7.

There are other aspects of Drupal that we will touch upon in this book, including taxonomies (sometimes called categories), filters, and actions. But there is no in-depth discussion of these here. To learn more, consult the Drupal handbooks: http://drupal.org/handbooks.

Note

Chapters 8 and 9 will make use of filters and actions inside modules.

Developers' Tools

So far, we've looked at some of the preliminary concepts involved in Drupal development. To finish off this chapter, we will switch focus to development tools.

There are a few Drupal-specific tools that you might find helpful when creating your own modules. These tools are themselves provided by two modules, which can both can be obtained from the Drupal site.

Developer Module

The Devel Module provides several tools that are extremely useful for Drupal development, including cache management, SQL debugging tools, investigation tools, a module reinstaller, an API reference tool, and many more.

You can find out more about this module at the official website: http://drupal.org/project/devel.

The main part of this module (the Devel module) provides these tools as items in a block. So after installing the module, you will need to go to Administer | Site building | Modules and enable the module, and then go to Administer | Site building | Blocks to tell Drupal where to display the new content.

This module also includes tools for building themes, a macro generator to simulate form data entry, and a tool to generate testing data. As the module continues to improve, new features will be added as well.

Any serious module developer will want to install the Devel module. In the writing of this book, it has proven an invaluable tool for reinstalling modules, clearing caches, and debugging difficult code.

Coder Module

As we shall see in this book, Drupal developers adhere to strict conventions in their code. The Coder Module is a tool designed to help you, the developer, locate and fix code that does not adhere to these conventions.

In addition to making sure code follows conventions, it also does some basic security auditing regarding how text is handled. This can be useful for spotting mistakes before they become security risks.

The Coder Module is also hosted on the official Drupal site: http://drupal.org/project/coder.

While it does not improve productivity in the same way that the Devel module does, Coder can help you generate clean and "Drupalish" code. Its strict syntax checking also occasionally turns up bugs.

Note

"Drupalish"

Drupal developers are fond of using the word Drupalish to refer to practices, styles, and approaches that mesh well with the Drupal philosophy. For example, Drupalish code adheres to coding guidelines and makes use of data structures common in Drupal (like nested associative arrays).

In addition to these modules, there is a wealth of information on the Drupal website about how to configure your favorite development environment (including Emacs, VI, FireBug, and Eclipse PDT) for Drupal development: http://drupal.org/node/147789.

A Word on Our Demonstration Site

Since this book focuses on development, we won't walk through the standard process of downloading, installing, and configuring Drupal. If you need to review any of this information, the Drupal website at http://drupal.org has a complete installation handbook. We will begin assuming that Drupal is already installed and configured.

In this book, we will develop modules for a fictional website called Philosopher Bios. This website provides news and biographical sketches of famous philosophers. Most of the modules we develop in this book will be reflective of the kind of functionality such a site would need.

While this is the theme of the website, the modules we create will be broadly applicable to other sites, and are reflective (I hope) of the sorts of real-world applications that we commonly develop for Drupal.

I've tried to come up with unique modules (not re-inventing the wheel). However, with such a popular and mature platform, it seems inevitable that I have repeated something someone has already done. The primary goal of the modules presented in this book, though, is to provide instructive and practical examples of Drupal modules.

Summary

This chapter is an introduction to Drupal's architecture. Taking a developer's perspective, we examined the basic structure of Drupal. After that, we looked at some of the concepts and systems that will be important in this book.

Now that this preliminary chapter is done, we are going to shift focus. No more theory‑laden chapters and high-level explanations. From here on, our focus will be practical.

In the next chapter, we will build our first module—and no, it's not going to be a garden‑variety "Hello, World" module. We will use a remote XML-based API to fetch content and display it as a Drupal block. So strap yourself in, and let's get coding.

A Basic .module File

As mentioned in the first chapter, there are two files that every module must have (though many modules have more). The first, the .info file, we examined above. The second file is the .module (dot-module) file, which is a PHP script file. This file typically implements a handful of hook functions that Drupal will call at pre-determined times during a request.

Note

For an introduction to hooks and hook implementations, see the previous chapter.

Here, we will create a .module file that will display a small formatted section of information. Later in this chapter, we will configure Drupal to display this information to site visitors.