Monthly Archives: April 2011

Simple value getter and setter for CakePHP

This snipped I’ve wrote, because I think it’s convenient to have something like this in cake.

Put this in AppModel (/youur_cake_project/app/app_model.php)

<?php
class AppModel extends Model {
    /**
     * handy method for getting and setting value in a model.
     * For setter: it's not validating anything, so bear in mind...
     * Usage:
     *   Getter:
     *    $this->MyModel->id = 5;
     *    $this->MyModel->value('name'); //retun value of column name for the id 5
     *   Setter
     *    $this->MyModel->id = 5;
     *    $this->MyModel->value('name', 'BlaBla'); //set the name of row with id 5 to BlaBla
     */

      public function value($field, $value = null){
    if(func_num_args() == 1){ //getter
        $result = $this->field($field);
        if($result){
        return $result;
        }
    } else { //setter
        if($this->saveField($field, $value)){
        return true;
        }
    }
    return false;
     }
}?>

Getter:

$this->YourModel->id = 5; //set the id of the model
$this->YourModel->value('name');//return the value of the row with id 5

Setter:

$this->MyModel->id = 5; //set the id of the model
$this->MyModel->value('name', 'BlaBla'); //set the name of row with id 5 to BlaBla

As you can see it’s not a rocket science, and it’s uses cake’s functions for this, but I thought it’s convenient to have such function.