Storing existing class objects

38 views
Skip to first unread message

Pierre Sarazin

unread,
Oct 16, 2016, 2:24:53 PM10/16/16
to redbeanphp
Hello all, I'm sure I'm just missing some logic from the manual, but I can't figure out how to use RB to store existing objects. All examples seem to create objects on the fly.

For example, how would one go about storing and retrieving objects for class A
class B
{
    private $b;
    public function __construct($b)
    {
        $this->b=$b;
    }
}
class A extends B {
    private $a1;
    public $a2;
    public function __construct()
    {
        $this->a1=1;
        $this->a2=2;
        parent::__construct(3);
    }
}

I've had a look at the option of using models.

class Model_A extends RedBean_SimpleModel {
    private $a1;
    public $a2;
    public function __construct()
    {
        $this->a1=1;
        $this->a2=2;
        parent::__construct(3);
    }
}

But properties are not stored in the DB, or retrieved from it, even if they are properties of the model. This happens wether the class members are private or public. There is also the issue that the class can't inherit from the base class B, since PHP doesn't support multiple inheritance

Essentially, I want to build strictly defined classes within PHP, but easily save and restore the objects from the DB.

I'm assuming I'm missing something trivial...

gabor

unread,
Oct 16, 2016, 2:29:55 PM10/16/16
to redbeanphp


Hi there,

Welcome to the RedBeanPHP forum.

You're trying to force RedBean into something that it isnt.
In RedBeanPHP you work with beans, so you should simply create a bean of type 'a':

$a = R::dispense( 'a' );
$a->message = 'hello';
R::store( $a );

Now if you want to attach additional logic to the bean, you can use a model:

class Model_A extends RedBean_SimpleModel {

  public function update() {
     echo $this->bean->message;
  }
}

you can access the bean through the model using $this->bean.
You can't use PHP classes as beans, that's not how RedBean works.

Hope this helps.

Cheers,
Gabor de Mooij

Pierre Sarazin

unread,
Oct 17, 2016, 11:49:04 AM10/17/16
to redbeanphp
Humm, 

Thanks for the information, and the tool! I guess I have to decide if rapid development is more important than decoupling the classes from the storage model.

Cheers, 

Pierre

gabor

unread,
Oct 19, 2016, 11:38:58 AM10/19/16
to redbeanphp

Strictly speaking the 2 are separated, your model does not know anything about the storage engine, it just processes beans.
It's just that it does not control the schema.
Reply all
Reply to author
Forward
0 new messages