How does AOP (Aspect Oriented Programming) work in Drupal?
I have learned about AOP in terms of using it for logging and security, but how does it apply to Drupal?
Drupal mimics AOP paradigms through hooks, which basically allow developers to weave in bits of code during the flow of execution. You can take a look at the hooks a developer can implement on the list of Drupal hooks shown in the Drupal documentation site, which just lists the hooks invoked from Drupal core and its modules.
As a quick example, if I were developing a new node based module (nodes being the basic data form in Drupal), I have instant access to comments and taxonomy with no additional work on my part. the comment and taxonomy modules have the ability to hook into nodes, and provide that added functionality. So in that sense, I don't have to account for such features in my program but I am able to take advantage of that flexibility.
Drupal is a "multi-paradigm" framework, and only certain bits of it implement "a kind of" AOP:
Drupal's AOP paradigm might be better visualized as event-driven, and it all happens through Drupal's concept of hooks. For example, when you do the following:
mymodule_init()
functionWhat you are declaring is, in pseudo-code:
subscribe mymodule to "hook events" of type init
When Drupal's core then runs module_invoke_all('init')
, Drupal is saying:
notify all subscribers to "hook events" of type init that this has occurred
by passing any relevant arguments to them
and letting them run the code they define in their hook_init()
So while PHP is still a procedural language—and your mymodule_init()
could do all sorts of crazy, un-encapsulated things if you really wanted—Drupal is still in charge. Drupal in a sense decides whether or not to call your code in the first place.
In this way, Drupal is able to turn its own execution phases into quasi-AOP, by defining joint points (the module_invoke*()
functions) and letting you write your own pointcuts (your mymodule_*()
function, whose naming convention must match Drupal's hook name.
For more background on this, and the multi-paradigmatic nature of Drupal especially, Programming language trade-offs, by Larry Garfield.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With