Drupalcon notes: Objectifying PHP
(No, PHP, your ass doesn't look fat in that. Honest.)
- Classes have interfaces, which declare which functions/methods it supports.
- A good object is atomic. It does one thing, and one thing well.
- Focus on making a good data object (pizza, cat, node). They don't have functionality. They just exist.
- Behavior objects are active, configurable, and do things.
- Be smart about how many dependencies you hard-code in.
-
Every function call or static method is a hard dependency!
- Good objects are opaque: it doesn't care what happens on the other side of the function. It should just know that it will get back a string, integer, whatever
- Drupal has a lot of circular dependencies, and this is a problem. Separation needs to happen. Doing so makes the code more testable and swappable.
So what should we actually do?
- Modules should become namespaces. Get out of the hook business. (We think.) Turning hooks into objects is not the way.
- What about the major systems, like theme, menu?
- Magic callbacks: lazy OOP without class
Good practices:
- Minimize extending
- Always provide an interface
- No exposed properties (if you expose a property, you don't know who has mucked with it)
- Don't be private (learn the difference between 'protected' and 'private' - properties should always be protected. methods should be public or protected depending on their needs)
- Constructor injection (don't just call out for a new object - pass info to it.)
Good for learning:
- martinfowler.com has a good article on constructor injection.
- Zandstra, Mark: PHP Objects, Patterns, and Practice (2008) Ignore everything it says about PHP 6
- planetphp.com
- garfieldtech.com - there's an OOP section