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;
}
}?>
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
$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
$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.
“$value == null” should be at least with === since those will call the getter, not the getter;
$model->value(‘amount’, 0);
$model->value(‘visible’, false);
For functionalities from this kind when I was writing php, I generally used func_num_args for checking the arguments.
Hi, you are completely right. Especially for the cases with 0 and false. Thanks!
Couldn’t you use the magic __get() and __set() methods for this purpose?