Skip to content

Instantly share code, notes, and snippets.

@al-the-x
Created July 27, 2014 20:00
Show Gist options
  • Save al-the-x/ed8969f5c53bc4340663 to your computer and use it in GitHub Desktop.
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?
<?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);
}
}
}
<?php
class User extends Model
{
// business logic methods go here...
}
User::init(function($options){
$this; // is bound to Model instance...
});
@al-the-x
Copy link
Author

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 each Model subclass to make this memory-manageable, as in Lithium's ORM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment