Optimizer

From RedBean

Jump to: navigation, search

Creating your own Optimizer

RedBean determines the type of column required for a specific value on the fly. If the type is too narrow you can correct this after the development phase when you freeze the database. However, there is another way. If you work with certain column types frequently RedBean can adjust these columns for you automatically. This is called optimization.

Optimizers are there to support specific column types. Out of the box, RedBean comes with two optimizers: datetime and shrink. Datetime tries to convert columns to a datetime column and shrink tries to fit existing columns into smaller types to save space or correct mistakes (accidental inserts or updates).

Implementing your own Optimizer is easy. Just create your optimizer class and make sure it implements the Redbean_Plugin_IOptimizer interface. For examples take a look at the default optimizers.

Example

Imagine we are building an optimizer to support ENUM() types. In this case we implement the IOptimizer interface like this:

class RedBean_Plugin_Optimizer_Enum implements RedBean_Plugin_IOptimizer {
public function setTable($table){  
$this->table = $table; 
 }
public function setColumn($column) { 
$this->column = $column;
}
public function setValue($value){
$this->value = $value;
}
public function optimize() {
//do some SQL to check if we can convert this table-column-value to ENUM()
}
}

Your optimize() function should return TRUE if you want further optimizations to take place or FALSE otherwise.

To attach your Optimizer:

$optimizer = new RedBean_Plugin_Optimizer( $toolbox );
$optimizer->addOptimizer(new RedBean_Plugin_Optimizer_Enum($toolbox));
$redbean->addEventListener("update", $optimizer);
Personal tools