18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Node Access<br />

The reasoning behind this rule is that advanced access rules are more likely to be<br />

applied to the View operation; many sites only require access restrictions on who can<br />

view content because only editors and administrators may create content.<br />

If you implement hook_node_access() on the View operation, you<br />

are likely to alter the expected node access behavior in ways that make<br />

debugging difficult for the site owner and other module developers.<br />

Therefore, only node access modules should assert rules on the View<br />

operation; access control modules should refrain from doing so.<br />

If you think you must enforce View rules in hook_node_access(), please<br />

clearly document that you have done so on your module's project page and<br />

in an accompanying README.txt file.<br />

When to write a node access module<br />

Clearly, hook_node_access() is a very powerful function. As we have seen, many<br />

common use-cases can be solved in just a few lines of code. So it is important for<br />

module developers to consider when to use hook_node_access() to implement<br />

access control as opposed to a complete node access module.<br />

Since access control modules should not respond to the View operation, node access<br />

modules become necessary any time you need to use access rules to restrict access<br />

to the nodes that a user may view. The reason for this has to do with how <strong>Drupal</strong><br />

builds its access controls when listing nodes. hook_node_access() is only effective<br />

for running access checks against individual nodes – a fact made clear by the fact that<br />

the $node object is passed as a parameter.<br />

However, hook_node_access() is no use to us when generating a list of nodes, for<br />

three reasons:<br />

• It provides no means to alter a node listing query to produce a proper list of<br />

accessible nodes.<br />

• Running an individual lookup function for every node on a page can be<br />

resource intensive.<br />

• An implementation of hook_node_access() can overrule the behavior<br />

defined by other modules, which may not be desirable.<br />

While it is tempting to solve all your access needs with hook_node_access(), doing<br />

so limits the flexibility of your module. hook_node_access() is recommended for<br />

single use-case modules, particularly those written for a specific site or project.<br />

[ 260 ]

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

Saved successfully!

Ooh no, something went wrong!