Domain Object
From RedBean
In real world applications you often don't work with beans, you work with Models instead. One way to connect the beans to models is to use the Domain Object. Because you might find it quite convenient it ships with RedBean.
Example Usage of the Domain Object
The Domain Object is just a little extra convenience object you might want to use. It allows you to wrap beans in Models. The Model constructor takes a type name to be used for the bean; if no type is given, the domain object will infer its type name using the name of the class.
class Book extends RedBean_DomainObject {
public function getTitle() {
return $this->bean->title;
}
public function setTitle( $title ) {
$this->bean->title = $title;
}
public function addAuthor( Author $author ) {
$this->associate($author);
}
public function getAuthors() {
return $this->related( new Author );
}
}
class Author extends RedBean_DomainObject {
public function setName( $name ) {
$this->bean->name = $name;
}
public function getName() {
return $this->bean->name;
}
}
Usage:
$book = new Book;
$author = new Author;
$book->setTitle("A can of beans");
$author->setName("Mr. Bean");
$book->addAuthor($author);
$id = $book->getID();
$authors = $book->getAuthors();
The domain object class has some very useful protected methods that resemble bean methods:
- related( $className, $constructorArg = null )
- associate(RedBean_DomainObject $other)
- unassociate(RedBean_DomainObject $other)
- set1toNAssoc(RedBean_DomainObject $other)
- clearRelations() -- clears associations
- find($id) -- returns model of same type with id $id
- attach(RedBean_DomainObject $other) -- for trees.

