PHP Redbean, Custom model & Custom Properties (non-saving)
You might want custom properties on your beans in redbean
, such as if you want to do $bean->url
but you don't save a url in the databse. perhaps you save a slug
, and the url ends up being https://taeluf.com/funny-cats/THE_SLUG/
. Or something like the example below that concatenates first name & last name.
Note that I use RDB
instead of R
. This was a quick change to the redbean source code. R
caused conflicts in my project.
- Write a
CustomProps
class to modify built-in behavior - Write a model that uses the custom property feature
- Enable your Custom Props class & Your model namespace
- Use it!
Step 1 - Extend Redbean
namespace RDBBean;
class CustomProps extends \RedBeanPHP\OODBBean {
//With how redbean works, the `&` for return-by-reference is required (I think)
public function &__get($prop){
$model = $this->box();
if (method_exists($model,$method='get'.ucfirst($prop)))return $model->$method();
return parent::__get($prop);
}
}
Step 2 - Create a Model
namespace RDBModel;
class Person extends \Redbean_SimpleModel {
public function &getFullName(){
$name = $this->bean->firstName.' '.$this->bean->lastName;
return $name;
}
}
Step 3 - Tell Redbean about your extensions
define('REDBEAN_MODEL_PREFIX', '\\RDBModel\\');
define('REDBEAN_OODBBEAN_CLASS', '\\RDBBean\\CustomProps');
Step 4 - Use the bean's custom prop!
$person = \RDB::findOne('person','id=?',[1]);
$fullName = $person->fullName;
echo $fullname;