Search code examples
phpredbean

RedBeanPhp how to create an active record model


anyone know it is possible to convert this:

$u = R::dispense('users');
$u->login = $this->login;
$u->password = $this->password;
R::store($u);

into this:

class User
{
    var $login;
    var $password;
    var $id;

    public function save() {
        $u = R::dispense('users');
        $u->login = $this->login;
        $u->password = $this->password;
        $this->id = R::store($u);
    }
}

$u = new User();
$u->login = 'login';
$u->password = 'pass';
$u->save();

but without using code on save some thing like this

public function save() {
    R::store($this);
}

Im sick and tired of rewritting statements like $u->login = $this->login;

many thanks


Solution

  • You should create a users model that extends Redbean's simple model like so:

    class Model_users extends \RedBean_SimpleModel
    {
        private $_login = 'My default login name';
        private $_password = 'My default not so secret password';
    
        // The following method is executed right before an insert or update
        function update()
        {
            $this->bean->login = $this->_login;
            $this->bean->password = $this->_password;
        }
    }
    

    Then you can simply use:

    $user = R::dispense('users');
    R::store($user);
    

    Good luck!