Created
July 27, 2014 20:00
-
-
Save al-the-x/ed8969f5c53bc4340663 to your computer and use it in GitHub Desktop.
Another thought about PHP ORMs that occurred to me today, should I ever fall victim to that particular land war in Asia... What if a Model class exposed a static method for configuration of child classes, which accepted a Closure that was invoked upon instantiation, like `Model#initialize` in Ruby?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Model | |
{ | |
static $hooks = [ ]; | |
/** | |
* Add initialization hook $init to (FIFO) queue, which will be bound to the | |
* instance of the object at initialization. | |
* | |
* @param Closure $init hook to add to (FIFO) queue | |
*/ | |
static method init(Closure $init){ | |
static::$hooks['init'][] = $init; | |
} | |
function __construct($options = []){ | |
// . . . | |
foreach ( static::$hooks['init'] as $init ){ | |
$init = $init->bindTo($this, $this); | |
$init($options); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class User extends Model | |
{ | |
// business logic methods go here... | |
} | |
User::init(function($options){ | |
$this; // is bound to Model instance... | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In retrospect, I don't really like this pattern much in PHP. The Closures represent a memory leak, since they get cloned in
Model.php:20
as a result of binding them. There would need to be very few instances of eachModel
subclass to make this memory-manageable, as in Lithium's ORM.