...

View Full Version : MVC : Dynamically adding functionnalities to a model class



Neuromancer2
03-29-2010, 03:54 PM
Hello,

I am writing a basic PHP framework for my personal use. I have an abstract model class :

abstract class Model {
public function save() {
/* Save data */
}

public function delete() {
/* Delete a record */
}
}
I create model classes extending the base Model class, for instance :

class ArticleModel extends Model {
...
}
I would like to add functionalities to my models in a flexible manner and so that I would be able to reuse them (publication, trash bin, translation...). I already have a event system based on the observer pattern which allow me to attach listeners to an object. It's quite useful but I need the ability to add new operations to existing object. I am wondering what kind of approach/pattern would be more suitable.
The decorator pattern allow to add dynamically functionalities to an object.


class TrashBinDecorator {

private $model = null;

public function __construct( Model $model ) {
$this->model = $model;
}

public function delete() {
// overriding the delete() method
}

public function restore() {
// ...
}
}

$article = new TrashBinDecorator( Article::findOne( 3 ) );

But I use finders methods to create the model objets :

$article = Article::findOne( 3 );
$articles = Article::findAll();
My idea is to use a configurable factory to create model instances :


public static function findOne {
// executing the database query

// creating the model instance
$model = Factory::create( get_class( self ) );
// ...
return $model;
}

The factory should be able to create a decorated instance using a configuration file :

class Factory {
public static function create( $className ) {
$object = new $className();
foreach( $decorators as $decorator ) {
$object = new $decorator( $object );
}
}
}

If I would like to add a functionality to a model, I simply would have to modify a configuration file.

What do you think of this approach ?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum