Fuse
From RedBean
Fuse
Fuse is a new technology in RedBean 1.1 that allows you to easily add validation rules to beans.
Importing user data and storing it with RedBean is really simple:
$comment = R::dispense("comment");
$comment->import($_POST,"nickname,message");
R::store( $comment );
But how do you prevent users from using illegal nicknames? Of course you could check before you import the bean:
if (preg_match( $regexRule, $_POST["nickname"] )) { ... }
But this easily leads to validation rules scattering all over the place. It's better to put these rules into a model; but then you cannot use import() anymore? Well, actually with Fuse you can.
To add a validation rule to comment beans we type:
class Model_Comment extends RedBean_SimpleModel {
public function update() {
if (!preg_match( $somePattern, $this->nickname )) {
throw new Exception("Illegal nickname!");
}
}
}
$comment = R::dispense("comment");
$comment->import($_POST,"nickname,message");
R::store( $comment );
This will just work; RedBean will auto-discover the model and all
events (update, open, delete) will be handled by this model.
How it works
Fuse adds an event listener to the RedBean object database. If an event occurs it creates an instance of the model that belongs to the bean. It looks for a class with the name Model_X where X is the type of the bean. If such a model exists, it creates an instance of that model and calls loadBean(), passing the bean. This will copy the bean to the internal bean property of the model (defined by the superclass SimpleModel). All bean properties will become accessible to $this because Fuse relies on magic getters and setters.

