18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9<br />

Writing a complete node access module, on the other hand, is a more complex task,<br />

and one that we will examine in detail in the rest of this chapter. The advantages to<br />

writing a node access module are:<br />

• Node access modules can work in conjunction with other modules to provide<br />

flexible access control rules.<br />

• Node access rules set by one module may be modified by any other module,<br />

whereas hook_node_access() implementations cannot.<br />

• Node access modules typically address common usage scenarios and are<br />

therefore re-usable by more people. While this is not a technical advantage,<br />

it is a great reason to contribute code to the <strong>Drupal</strong> project.<br />

The {node_access} table and its role<br />

The primary difference between access control modules and node access modules<br />

is the use of the {node_access} table. When a node access module is installed,<br />

database queries for the {node} table can be JOINed to the {node_access}<br />

table in order to delimit the list of returned values.<br />

By default, the {node_access} table contains a single record which allows all<br />

content to be viewed by all users (except those who cannot access content,<br />

as we saw when looking at the node_access() function).<br />

When a node access module is enabled, however, this default record is removed,<br />

and node queries will be modified appropriately. Let's look again at a sample<br />

query-builder function that returns a simple list of published nodes:<br />

$select = db_select('node', 'n')<br />

->fields('n', array('nid'))<br />

->condition('promote', 1)<br />

->condition('status', 1)<br />

->orderBy('sticky', 'DESC')<br />

->orderBy('created', 'DESC')<br />

->extend('PagerDefault')<br />

->limit(10)<br />

->addTag('node_access');<br />

$nids = $select->execute()->fetchCol();<br />

[ 261 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!