Posted by Chris Charlton on March 30, 2009 at 9:41pm
I'd recommend folks look at a project called DrOOPal, by our LA Drupal member Brendon Crawford.
Project page: http://drupal.org/project/droopal
Documentation: http://drupal.org/node/304775
Example of writing custom modules using OOP structures:
<?php
class ModMyModule {
// hook_menu
function menu() {
//etc...
}
// hook_nodeapi
function nodeapi() {
//etc...
}
}
?>
Comments
No
I simply do not understand why people keep suggesting module == class. I've explained before that it is a bad idea. Classes as a concept are fundamentally different than how modules work in Drupal. Modules are closer to a namespace, and classes are not a namespace. They create a sorta namespace as a side effect, but that's not what they are. Classes are a data type. Modules are not a data type.
If we were to convert all modules to classes, it would have the following effects:
1) The entirety of a module would have to live in a single file. That means all of the work in Drupal 6 to push page callbacks out into conditional files (which gave us a 20% performance boost) would have to be undone. It also means install hooks and update hooks would have to go back into one huge class file. That means we would have to load every single bit of code in all of Drupal for every page load (huge memory and CPU drain), we would be forced to have multi-thousand-line files for any even reasonably interesting module.
2) We would have to actively instantiate every module/class on every page load. That burns still more CPU cycles. Unless of course your intent is to use everything as a static method, in which case function prefixing like Drupal already does is faster and less confusing, since inheritance doesn't work properly for static methods anyway in PHP 5.2 and earlier.
3) It would be impossible to implement a hook on another module's behalf. That is, all of those places where, say, Views implements hooks on behalf of a half-dozen core modules would be impossible, since you can't declare a class twice. All modules would have to be entirely self-contained, and we could not have bridge modules that link two other modules together via hook implementations.
So in short, module == class would be a catastrophic performance disaster and obliterate half of the useful functionality in Drupal. No, we are not going to do that.
The module == class concept is frankly born of naivete about both OOP and Drupal's architecture. There are plenty of places where classes would be useful in Drupal. As modules is perhaps the absolute worst place they could be used.