\RedBeanPHPOODBBean

OODBBean (Object Oriented DataBase Bean).

to exchange information with the database. A bean represents a single table row and offers generic services for interaction with databases systems as well as some meta-data.

Summary

Methods
Properties
Constants
useFluidCount()
setEnforceUTF8encoding()
setErrorHandlingFUSE()
convertArraysToJSON()
aliases()
getAliases()
setMetaAll()
initializeForDispense()
setBeanHelper()
getIterator()
import()
trimport()
importRow()
importFrom()
inject()
export()
__isset()
exists()
getID()
__unset()
either()
with()
withCondition()
all()
noLoad()
alias()
getProperties()
getPropertiesAndType()
beau()
clearModifiers()
isListInExclusiveMode()
__get()
__set()
setProperty()
getMeta()
info()
moveMeta()
setMeta()
copyMetaFrom()
captureDynamicCasting()
__call()
__toString()
offsetSet()
offsetExists()
offsetUnset()
offsetGet()
fetchAs()
poly()
traverse()
count()
isEmpty()
setAttr()
unsetAll()
old()
isTainted()
hasChanged()
hasListChanged()
clearHistory()
link()
one()
fresh()
via()
countOwn()
countShared()
aggr()
equals()
jsonSerialize()
No public properties found
C_ERR_IGNORE
C_ERR_LOG
C_ERR_NOTICE
C_ERR_WARN
C_ERR_EXCEPTION
C_ERR_FUNC
C_ERR_FATAL
No protected methods found
$useFluidCount
$convertArraysToJSON
$errorHandlingFUSE
$errorHandler
$aliases
$enforceUTF8encoding
$properties
$__info
$beanHelper
$fetchType
$withSql
$withParams
$aliasName
$via
$noLoad
$all
$castProperty
N/A
getSharedList()
getOwnList()
No private properties found
N/A

Constants

C_ERR_IGNORE

C_ERR_IGNORE

FUSE error modes.

C_ERR_LOG

C_ERR_LOG

C_ERR_NOTICE

C_ERR_NOTICE

C_ERR_WARN

C_ERR_WARN

C_ERR_EXCEPTION

C_ERR_EXCEPTION

C_ERR_FUNC

C_ERR_FUNC

C_ERR_FATAL

C_ERR_FATAL

Properties

$useFluidCount

$useFluidCount : boolean

Type

boolean

$convertArraysToJSON

$convertArraysToJSON : boolean

Type

boolean

$errorHandlingFUSE

$errorHandlingFUSE : boolean

Type

boolean

$errorHandler

$errorHandler : callable|NULL

Type

callable|NULL

$aliases

$aliases : array

Type

array

$enforceUTF8encoding

$enforceUTF8encoding : boolean

If this is set to TRUE, the __toString function will encode all properties as UTF-8 to repair invalid UTF-8 encodings and prevent exceptions (which are uncatchable from within a __toString-function).

Type

boolean

$properties

$properties : array

This is where the real properties of the bean live. They are stored and retrieved by the magic getter and setter (__get and __set).

Type

array

$__info

$__info : array

Here we keep the meta data of a bean.

Type

array

$beanHelper

$beanHelper : \RedBeanPHP\BeanHelper|NULL

The BeanHelper allows the bean to access the toolbox objects to implement rich functionality, otherwise you would have to do everything with R or external objects.

Type

\RedBeanPHP\BeanHelper|NULL

$fetchType

$fetchType : string|NULL

Type

string|NULL

$withSql

$withSql : string

Type

string

$withParams

$withParams : array

Type

array

$aliasName

$aliasName : string|NULL

Type

string|NULL

$via

$via : string|NULL

Type

string|NULL

$noLoad

$noLoad : boolean

Type

boolean

$all

$all : boolean

Type

boolean

$castProperty

$castProperty : string|NULL

Type

string|NULL

Methods

useFluidCount()

useFluidCount(boolean  $toggle) : boolean

If fluid count is set to TRUE then $bean->ownCount() will return 0 if the table does not exists.

Only for backward compatibility. Returns previous value.

Parameters

boolean $toggle

toggle

Returns

boolean

setEnforceUTF8encoding()

setEnforceUTF8encoding(boolean  $toggle) : void

If this is set to TRUE, the __toString function will encode all properties as UTF-8 to repair invalid UTF-8 encodings and prevent exceptions (which are uncatchable from within a __toString-function).

Parameters

boolean $toggle

TRUE to enforce UTF-8 encoding (slower)

setErrorHandlingFUSE()

setErrorHandlingFUSE(integer  $mode, callable|NULL  $func = NULL) : array

Sets the error mode for FUSE.

What to do if a FUSE model method does not exist? You can set the following options:

  • OODBBean::C_ERR_IGNORE (default), ignores the call, returns NULL
  • OODBBean::C_ERR_LOG, logs the incident using error_log
  • OODBBean::C_ERR_NOTICE, triggers a E_USER_NOTICE
  • OODBBean::C_ERR_WARN, triggers a E_USER_WARNING
  • OODBBean::C_ERR_EXCEPTION, throws an exception
  • OODBBean::C_ERR_FUNC, allows you to specify a custom handler (function)
  • OODBBean::C_ERR_FATAL, triggers a E_USER_ERROR

Custom handler method signature: handler( array ( 'message' => string 'bean' => OODBBean 'method' => string ) )

This method returns the old mode and handler as an array.

Parameters

integer $mode

error handling mode

callable|NULL $func

custom handler

Returns

array

convertArraysToJSON()

convertArraysToJSON(boolean  $flag) : boolean

Toggles array to JSON conversion. If set to TRUE any array set to a bean property that's not a list will be turned into a JSON string. Used together with AQueryWriter::useJSONColumns this extends the data type support for JSON columns. Returns the previous value of the flag.

Parameters

boolean $flag

flag

Returns

boolean

aliases()

aliases(array  $list) : void

Sets global aliases.

Registers a batch of aliases in one go. This works the same as fetchAs and setAutoResolve but explicitly. For instance if you register the alias 'cover' for 'page' a property containing a reference to a page bean called 'cover' will correctly return the page bean and not a (non-existent) cover bean.

R::aliases( array( 'cover' => 'page' ) ); $book = R::dispense( 'book' ); $page = R::dispense( 'page' ); $book->cover = $page; R::store( $book ); $book = $book->fresh(); $cover = $book->cover; echo $cover->getMeta( 'type' ); //page

The format of the aliases registration array is:

{alias} => {actual type}

In the example above we use:

cover => page

From that point on, every bean reference to a cover will return a 'page' bean. Note that with autoResolve this feature along with fetchAs() is no longer very important, although relying on explicit aliases can be a bit faster.

Parameters

array $list

list of global aliases to use

getAliases()

getAliases() : array

Return list of global aliases

Returns

array

setMetaAll()

setMetaAll(array  $beans, string  $property, mixed  $value) : array

Sets a meta property for all beans. This is a quicker way to set the meta properties for a collection of beans because this method can directly access the property arrays of the beans.

This method returns the beans.

Parameters

array $beans

beans to set the meta property of

string $property

property to set

mixed $value

value

Returns

array

initializeForDispense()

initializeForDispense(string  $type, \RedBeanPHP\BeanHelper|NULL  $beanhelper = NULL) : void

Initializes a bean. Used by OODB for dispensing beans.

It is not recommended to use this method to initialize beans. Instead use the OODB object to dispense new beans. You can use this method if you build your own bean dispensing mechanism. This is not recommended.

Unless you know what you are doing, do NOT use this method. This is for advanced users only!

Parameters

string $type

type of the new bean

\RedBeanPHP\BeanHelper|NULL $beanhelper

bean helper to obtain a toolbox and a model

setBeanHelper()

setBeanHelper(\RedBeanPHP\BeanHelper  $helper) : void

Sets the Bean Helper. Normally the Bean Helper is set by OODB.

Here you can change the Bean Helper. The Bean Helper is an object providing access to a toolbox for the bean necessary to retrieve nested beans (bean lists: ownBean, sharedBean) without the need to rely on static calls to the facade (or make this class dep. on OODB).

Parameters

\RedBeanPHP\BeanHelper $helper

helper to use for this bean

getIterator()

getIterator() 

import()

import(array  $array, string|array  $selection = FALSE, boolean  $notrim = FALSE) : \RedBeanPHP\OODBBean

Imports all values from an associative array $array. Chainable.

This method imports the values in the first argument as bean property and value pairs. Use the second parameter to provide a selection. If a selection array is passed, only the entries having keys mentioned in the selection array will be imported. Set the third parameter to TRUE to preserve spaces in selection keys.

Parameters

array $array

what you want to import

string|array $selection

selection of values

boolean $notrim

if TRUE selection keys will NOT be trimmed

Returns

\RedBeanPHP\OODBBean

trimport()

trimport(array  $array, callable  $function = 'trim', string|array  $selection = FALSE, boolean  $notrim = FALSE) : \RedBeanPHP\OODBBean

Same as import() but trims all values by default.

Set the second parameter to apply a different function.

Parameters

array $array

what you want to import

callable $function

function to apply (default is trim)

string|array $selection

selection of values

boolean $notrim

if TRUE selection keys will NOT be trimmed

Returns

\RedBeanPHP\OODBBean

importRow()

importRow(array  $row) : self

Imports an associative array directly into the internal property array of the bean as well as the meta property sys.orig and sets the changed flag to FALSE.

This is used by the repository objects to inject database rows into the beans. It is not recommended to use this method outside of a bean repository.

Parameters

array $row

a database row

Returns

self

importFrom()

importFrom(\RedBeanPHP\OODBBean  $sourceBean) : \RedBeanPHP\OODBBean

Imports data from another bean. Chainable.

Copies the properties from the source bean to the internal property list.

Usage:

$copy->importFrom( $bean );

The example above demonstrates how to make a shallow copy of a bean using the importFrom() method.

Parameters

\RedBeanPHP\OODBBean $sourceBean

the source bean to take properties from

Returns

\RedBeanPHP\OODBBean

inject()

inject(\RedBeanPHP\OODBBean  $otherBean) : \RedBeanPHP\OODBBean

Injects the properties of another bean but keeps the original ID.

Just like import() but keeps the original ID. Chainable.

Parameters

\RedBeanPHP\OODBBean $otherBean

the bean whose properties you would like to copy

Returns

\RedBeanPHP\OODBBean

export()

export(boolean  $meta = FALSE, boolean  $parents = FALSE, boolean  $onlyMe = FALSE, array  $filters = array()) : array

Exports the bean as an array.

This function exports the contents of a bean to an array and returns the resulting array. Depending on the parameters you can also export an entire graph of beans, apply filters or exclude meta data.

Usage:

$bookData = $book->export( TRUE, TRUE, FALSE, [ 'author' ] );

The example above exports all bean properties to an array called $bookData including its meta data, parent objects but without any beans of type 'author'.

Parameters

boolean $meta

set to TRUE if you want to export meta data as well

boolean $parents

set to TRUE if you want to export parents as well

boolean $onlyMe

set to TRUE if you want to export only this bean

array $filters

optional whitelist for export

Returns

array

__isset()

__isset(string  $property) : boolean

Implements isset() function for use as an array.

This allows you to use isset() on bean properties.

Usage:

$book->title = 'my book'; echo isset($book['title']); //TRUE

The example illustrates how one can apply the isset() function to a bean.

Parameters

string $property

name of the property you want to check

Returns

boolean

exists()

exists(string  $property) : boolean

Checks whether a related bean exists.

For instance if a post bean has a related author, this method can be used to check if the author is set without loading the author. This method works by checking the related ID-field.

Parameters

string $property

name of the property you wish to check

Returns

boolean

getID()

getID() : string|NULL

Returns the ID of the bean.

If for some reason the ID has not been set, this method will return NULL. This is actually the same as accessing the id property using $bean->id. The ID of a bean is its primary key and should always correspond with a table column named 'id'.

Returns

string|NULL

__unset()

__unset(string  $property) : void

Unsets a property of a bean.

Magic method, gets called implicitly when performing the unset() operation on a bean property.

Parameters

string $property

property to unset

either()

either() : \RedBeanPHP\Util\Either

Returns the bean wrapped in an Either-instance.

This allows the user to extract data from the bean using a chain of methods without any NULL checks, similar to the ?? operator but also in a way that is compatible with older versions of PHP. For more details consult the documentation of the Either class.

Returns

\RedBeanPHP\Util\Either

with()

with(string  $sql, array  $bindings = array()) : \RedBeanPHP\OODBBean

Adds WHERE clause conditions to ownList retrieval.

For instance to get the pages that belong to a book you would issue the following command: $book->ownPage However, to order these pages by number use:

$book->with(' ORDER BY number ASC ')->ownPage

the additional SQL snippet will be merged into the final query.

Parameters

string $sql

SQL to be added to retrieval query.

array $bindings

array with parameters to bind to SQL snippet

Returns

\RedBeanPHP\OODBBean

withCondition()

withCondition(string  $sql, array  $bindings = array()) : \RedBeanPHP\OODBBean

Just like with(). Except that this method prepends the SQL query snippet with AND which makes it slightly more comfortable to use a conditional SQL snippet. For instance to filter an own-list with pages (belonging to a book) on specific chapters you can use:

$book->withCondition(' chapter = 3 ')->ownPage

This will return in the own list only the pages having 'chapter == 3'.

Parameters

string $sql

SQL to be added to retrieval query (prefixed by AND)

array $bindings

array with parameters to bind to SQL snippet

Returns

\RedBeanPHP\OODBBean

all()

all() : self

Tells the bean to (re)load the following list without any conditions. If you have an ownList or sharedList with a condition you can use this method to reload the entire list.

Usage:

$bean->with( ' LIMIT 3 ' )->ownPage; //Just 3 $bean->all()->ownPage; //Reload all pages

Returns

self

noLoad()

noLoad() : self

Tells the bean to only access the list but not load its contents. Use this if you only want to add something to a list and you have no interest in retrieving its contents from the database.

Usage:

$book->noLoad()->ownPage[] = $newPage;

In the example above we add the $newPage bean to the page list of book without loading all the pages first. If you know in advance that you are not going to use the contents of the list, you may use the noLoad() modifier to make sure the queries required to load the list will not be executed.

Returns

self

alias()

alias(string  $aliasName) : \RedBeanPHP\OODBBean

Prepares an own-list to use an alias. This is best explained using an example. Imagine a project and a person. The project always involves two persons: a teacher and a student. The person beans have been aliased in this case, so to the project has a teacher_id pointing to a person, and a student_id also pointing to a person. Given a project, we obtain the teacher like this:

$project->fetchAs('person')->teacher;

Now, if we want all projects of a teacher we cant say:

$teacher->ownProject

because the $teacher is a bean of type 'person' and no project has been assigned to a person. Instead we use the alias() method like this:

$teacher->alias('teacher')->ownProject

now we get the projects associated with the person bean aliased as a teacher.

Parameters

string $aliasName

the alias name to use

Returns

\RedBeanPHP\OODBBean

getProperties()

getProperties() : array

Returns properties of bean as an array.

This method returns the raw internal property list of the bean. Only use this method for optimization purposes. Otherwise use the export() method to export bean data to arrays.

Returns

array

getPropertiesAndType()

getPropertiesAndType() : array

Returns properties of bean as an array.

This method returns the raw internal property list of the bean. Only use this method for optimization purposes. Otherwise use the export() method to export bean data to arrays. This method returns an array with the properties array and the type (string).

Returns

array

beau()

beau(string  $property) : string

Turns a camelcase property name into an underscored property name.

Examples:

  • oneACLRoute -> one_acl_route
  • camelCase -> camel_case

Also caches the result to improve performance.

Parameters

string $property

property to un-beautify

Returns

string

clearModifiers()

clearModifiers() : self

Modifiers are a powerful concept in RedBeanPHP, they make it possible to change the way a property has to be loaded.

RedBeanPHP uses property modifiers using a prefix notation like this:

$book->fetchAs('page')->cover;

Here, we load a bean of type page, identified by the cover property (or cover_id in the database). Because the modifier is called before the property is accessed, the modifier must be remembered somehow, this changes the state of the bean. Accessing a property causes the bean to clear its modifiers. To clear the modifiers manually you can use this method.

Usage:

$book->with( 'LIMIT 1' ); $book->clearModifiers()->ownPageList;

In the example above, the 'LIMIT 1' clause is cleared before accessing the pages of the book, causing all pages to be loaded in the list instead of just one.

Returns

self

isListInExclusiveMode()

isListInExclusiveMode(string  $listName) : boolean

Determines whether a list is opened in exclusive mode or not.

If a list has been opened in exclusive mode this method will return TRUE, otherwise it will return FALSE.

Parameters

string $listName

name of the list to check

Returns

boolean

__get()

__get(string  $property) : mixed

Magic Getter. Gets the value for a specific property in the bean.

If the property does not exist this getter will make sure no error occurs. This is because RedBean allows you to query (probe) for properties. If the property can not be found this method will return NULL instead.

Usage:

$title = $book->title; $pages = $book->ownPageList; $tags = $book->sharedTagList;

The example aboves lists several ways to invoke the magic getter. You can use the magic setter to access properties, own-lists, exclusive own-lists (xownLists) and shared-lists.

Parameters

string $property

name of the property you wish to obtain the value of

Returns

mixed

__set()

__set(string  $property, mixed  $value) : void

Magic Setter. Sets the value for a specific property.

This setter acts as a hook for OODB to mark beans as tainted. The tainted meta property can be retrieved using getMeta("tainted"). The tainted meta property indicates whether a bean has been modified and can be used in various caching mechanisms.

Parameters

string $property

name of the property you wish to assign a value to

mixed $value

the value you want to assign

setProperty()

setProperty(string  $property, mixed  $value, boolean  $updateShadow = FALSE, boolean  $taint = FALSE) : void

Parameters

string $property

property

mixed $value

value

boolean $updateShadow

whether you want to update the shadow

boolean $taint

whether you want to mark the bean as tainted

getMeta()

getMeta(string  $path, mixed  $default = NULL) : mixed

Returns the value of a meta property. A meta property contains additional information about the bean object that will not be stored in the database. Meta information is used to instruct RedBeanPHP as well as other systems how to deal with the bean.

If the property cannot be found this getter will return NULL instead.

Example:

$bean->setMeta( 'flush-cache', TRUE );

RedBeanPHP also stores meta data in beans, this meta data uses keys prefixed with 'sys.' (system).

Parameters

string $path

path to property in meta data

mixed $default

default value

Returns

mixed

info()

info(string  $key, mixed  $default = NULL) : \RedBeanPHP\mixed;

Returns a value from the data bundle.

The data bundle might contain additional data send from an SQL query, for instance, the total number of rows. If the property cannot be found, the default value will be returned. If no default has been specified, this method returns NULL.

Parameters

string $key

key

mixed $default

default (defaults to NULL)

Returns

\RedBeanPHP\mixed;

moveMeta()

moveMeta(string  $path,   $value = NULL) : mixed

Gets and unsets a meta property.

Moves a meta property out of the bean. This is a short-cut method that can be used instead of combining a get/unset.

Parameters

string $path

path to property in meta data

$value

Returns

mixed

setMeta()

setMeta(string  $path, mixed  $value) : \RedBeanPHP\OODBBean

Stores a value in the specified Meta information property.

The first argument should be the key to store the value under, the second argument should be the value. It is common to use a path-like notation for meta data in RedBeanPHP like: 'my.meta.data', however the dots are purely for readability, the meta data methods do not store nested structures or hierarchies.

Parameters

string $path

path / key to store value under

mixed $value

value to store in bean (not in database) as meta data

Returns

\RedBeanPHP\OODBBean

copyMetaFrom()

copyMetaFrom(\RedBeanPHP\OODBBean  $bean) : \RedBeanPHP\OODBBean

Copies the meta information of the specified bean This is a convenience method to enable you to exchange meta information easily.

Parameters

\RedBeanPHP\OODBBean $bean

bean to copy meta data of

Returns

\RedBeanPHP\OODBBean

captureDynamicCasting()

captureDynamicCasting(string  $method) : self|NULL

Captures a dynamic casting.

Enables you to obtain a bean value as an object by type-hinting the desired return object using asX where X is the class you wish to use as a wrapper for the property.

Usage:

$dateTime = $bean->asDateTime()->date;

Parameters

string $method

method (asXXX)...

Returns

self|NULL

__call()

__call(string  $method, array  $args) : mixed

Sends the call to the registered model.

This method can also be used to override bean behaviour. In that case you don't want an error or exception to be triggered if the method does not exist in the model (because it's optional). Unfortunately we cannot add an extra argument to __call() for this because the signature is fixed. Another option would be to set a special flag ( i.e. $this->isOptionalCall ) but that would cause additional complexity because we have to deal with extra temporary state. So, instead I allowed the method name to be prefixed with '@', in practice nobody creates methods like that - however the '@' symbol in PHP is widely known to suppress error handling, so we can reuse the semantics of this symbol. If a method name gets passed starting with '@' the overrideDontFail variable will be set to TRUE and the '@' will be stripped from the function name before attempting to invoke the method on the model. This way, we have all the logic in one place.

Parameters

string $method

name of the method

array $args

argument list

Returns

mixed

__toString()

__toString() : string

Implementation of __toString Method Routes call to Model. If the model implements a __toString() method this method will be called and the result will be returned. In case of an echo-statement this result will be printed. If the model does not implement a __toString method, this method will return a JSON representation of the current bean.

Returns

string

offsetSet()

offsetSet(  $offset,   $value) 

Parameters

$offset
$value

offsetExists()

offsetExists(  $offset) 

Parameters

$offset

offsetUnset()

offsetUnset(  $offset) 

Parameters

$offset

offsetGet()

offsetGet(  $offset) 

Parameters

$offset

fetchAs()

fetchAs(string  $type) : \RedBeanPHP\OODBBean

Chainable method to cast a certain ID to a bean; for instance: $person = $club->fetchAs('person')->member; This will load a bean of type person using member_id as ID.

Parameters

string $type

preferred fetch type

Returns

\RedBeanPHP\OODBBean

poly()

poly(string  $field) : \RedBeanPHP\OODBBean

Prepares to load a bean using the bean type specified by another property.

Similar to fetchAs but uses a column instead of a direct value.

Usage:

$car = R::load( 'car', $id ); $engine = $car->poly('partType')->part;

In the example above, we have a bean of type car that may consists of several parts (i.e. chassis, wheels). To obtain the 'engine' we access the property 'part' using the type (i.e. engine) specified by the property indicated by the argument of poly(). This essentially is a polymorph relation, hence the name. In database this relation might look like this:

partType | part_id

engine | 1020300 wheel | 4820088 chassis | 7823122

Parameters

string $field

field name to use for mapping

Returns

\RedBeanPHP\OODBBean

traverse()

traverse(string  $property, callable  $function, integer|NULL  $maxDepth = NULL,   $depth = 1) : \RedBeanPHP\OODBBean

Traverses a bean property with the specified function.

Recursively iterates through the property invoking the function for each bean along the way passing the bean to it.

Can be used together with with, withCondition, alias and fetchAs.

$task ->withCondition(' priority >= ? ', [ $priority ]) ->traverse('ownTaskList', function( $t ) use ( &$todo ) { $todo[] = $t->descr; } );

In the example, we create a to-do list by traversing a hierarchical list of tasks while filtering out all tasks having a low priority.

Parameters

string $property

property

callable $function

function

integer|NULL $maxDepth

maximum depth for traversal

$depth

Throws

\RedBeanPHP\RedException

Returns

\RedBeanPHP\OODBBean

count()

count() 

isEmpty()

isEmpty() : boolean

Checks whether a bean is empty or not.

A bean is empty if it has no other properties than the id field OR if all the other properties are 'empty()' (this might include NULL and FALSE values).

Usage:

$newBean = R::dispense( 'bean' ); $newBean->isEmpty(); // TRUE

The example above demonstrates that newly dispensed beans are considered 'empty'.

Returns

boolean

setAttr()

setAttr(string  $property, mixed  $value) : \RedBeanPHP\OODBBean

Chainable setter.

This method is actually the same as just setting a value using a magic setter (->property = ...). The difference is that you can chain these setters like this:

Usage:

$book->setAttr('title', 'mybook')->setAttr('author', 'me');

This is the same as setting both properties $book->title and $book->author. Sometimes a chained notation can improve the readability of the code.

Parameters

string $property

the property of the bean

mixed $value

the value you want to set

Returns

\RedBeanPHP\OODBBean

unsetAll()

unsetAll(array  $properties) : \RedBeanPHP\OODBBean

Convenience method.

Unsets all properties in the internal properties array.

Usage:

$bean->property = 1; $bean->unsetAll( array( 'property' ) ); $bean->property; //NULL

In the example above the 'property' of the bean will be unset, resulting in the getter returning NULL instead of 1.

Parameters

array $properties

properties you want to unset.

Returns

\RedBeanPHP\OODBBean

old()

old(string  $property) : mixed

Returns original (old) value of a property.

You can use this method to see what has changed in a bean. The original value of a property is the value that this property has had since the bean has been retrieved from the databases.

$book->title = 'new title'; $oldTitle = $book->old('title');

The example shows how to use the old() method. Here we set the title property of the bean to 'new title', then we obtain the original value using old('title') and store it in a variable $oldTitle.

Parameters

string $property

name of the property you want the old value of

Returns

mixed

isTainted()

isTainted() : boolean

Convenience method.

Returns TRUE if the bean has been changed, or FALSE otherwise. Same as $bean->getMeta('tainted'); Note that a bean becomes tainted as soon as you retrieve a list from the bean. This is because the bean lists are arrays and the bean cannot determine whether you have made modifications to a list so RedBeanPHP will mark the whole bean as tainted.

Returns

boolean

hasChanged()

hasChanged(string  $property) : boolean

Returns TRUE if the value of a certain property of the bean has been changed and FALSE otherwise.

Note that this method will return TRUE if applied to a loaded list. Also note that this method keeps track of the bean's history regardless whether it has been stored or not. Storing a bean does not undo its history, to clean the history of a bean use: clearHistory().

Parameters

string $property

name of the property you want the change-status of

Returns

boolean

hasListChanged()

hasListChanged(string  $property) : boolean

Returns TRUE if the specified list exists, has been loaded and has been changed: beans have been added or deleted.

This method will not tell you anything about the state of the beans in the list.

Usage:

$book->hasListChanged( 'ownPage' ); // FALSE array_pop( $book->ownPageList ); $book->hasListChanged( 'ownPage' ); // TRUE

In the example, the first time we ask whether the own-page list has been changed we get FALSE. Then we pop a page from the list and the hasListChanged() method returns TRUE.

Parameters

string $property

name of the list to check

Returns

boolean

clearHistory()

clearHistory() : self

Clears (syncs) the history of the bean.

Resets all shadow values of the bean to their current value.

Usage:

$book->title = 'book'; echo $book->hasChanged( 'title' ); //TRUE R::store( $book ); echo $book->hasChanged( 'title' ); //TRUE $book->clearHistory(); echo $book->hasChanged( 'title' ); //FALSE

Note that even after store(), the history of the bean still contains the act of changing the title of the book. Only after invoking clearHistory() will the history of the bean be cleared and will hasChanged() return FALSE.

Returns

self

link()

link(string|\RedBeanPHP\OODBBean  $typeOrBean, string|array  $qualification = array()) : \RedBeanPHP\OODBBean

Creates a N-M relation by linking an intermediate bean.

This method can be used to quickly connect beans using indirect relations. For instance, given an album and a song you can connect the two using a track with a number like this:

Usage:

$album->link('track', array('number'=>1))->song = $song;

or:

$album->link($trackBean)->song = $song;

What this method does is adding the link bean to the own-list, in this case ownTrack. If the first argument is a string and the second is an array or a JSON string then the linking bean gets dispensed on-the-fly as seen in example #1. After preparing the linking bean, the bean is returned thus allowing the chained setter: ->song = $song.

Parameters

string|\RedBeanPHP\OODBBean $typeOrBean

type of bean to dispense or the full bean

string|array $qualification

JSON string or array (optional)

Returns

\RedBeanPHP\OODBBean

one()

one(  $type) : \RedBeanPHP\OODBBean

Returns a bean of the given type with the same ID of as the current one. This only happens in a one-to-one relation.

This is as far as support for 1-1 goes in RedBeanPHP. This method will only return a reference to the bean, changing it and storing the bean will not update the related one-bean.

Usage:

$author = R::load( 'author', $id ); $biography = $author->one( 'bio' );

The example loads the biography associated with the author using a one-to-one relation. These relations are generally not created (nor supported) by RedBeanPHP.

Parameters

$type

type of bean to load

Returns

\RedBeanPHP\OODBBean

fresh()

fresh() : \RedBeanPHP\OODBBean

Reloads the bean.

Returns the same bean freshly loaded from the database. This method is equal to the following code:

$id = $bean->id; $type = $bean->getMeta( 'type' ); $bean = R::load( $type, $id );

This is just a convenience method to reload beans quickly.

Usage:

R::exec( ...update query... ); $book = $book->fresh();

The code snippet above illustrates how to obtain changes caused by an UPDATE query, simply by reloading the bean using the fresh() method.

Returns

\RedBeanPHP\OODBBean

via()

via(string  $via) : \RedBeanPHP\OODBBean

Registers a association renaming globally.

Use via() and link() to associate shared beans using a 3rd bean that will act as an intermediate type. For instance consider an employee and a project. We could associate employees with projects using a sharedEmployeeList. But, maybe there is more to the relationship than just the association. Maybe we want to qualify the relation between a project and an employee with a role: 'developer', 'designer', 'tester' and so on. In that case, it might be better to introduce a new concept to reflect this: the participant. However, we still want the flexibility to query our employees in one go. This is where link() and via() can help. You can still introduce the more applicable concept (participant) and have your easy access to the shared beans.

$Anna = R::dispense( 'employee' ); $Anna->badge = 'Anna'; $project = R::dispense( 'project' ); $project->name = 'x'; $Anna->link( 'participant', array( 'arole' => 'developer' ) )->project = $project; R::storeAll( array( $project, $Anna ) ); $employees = $project ->with(' ORDER BY badge ASC ') ->via( 'participant' ) ->sharedEmployee;

This piece of code creates a project and an employee. It then associates the two using a via-relation called 'participant' ( employee <-> participant <-> project ). So, there will be a table named 'participant' instead of a table named 'employee_project'. Using the via() method, the employees associated with the project are retrieved 'via' the participant table (and an SQL snippet to order them by badge).

Parameters

string $via

type you wish to use for shared lists

Returns

\RedBeanPHP\OODBBean

countOwn()

countOwn(string  $type) : integer

Counts all own beans of type $type.

Also works with alias(), with() and withCondition(). Own-beans or xOwn-beans (exclusively owned beans) are beans that have been associated using a one-to-many relation. They can be accessed through the ownXList where X is the type of the associated beans.

Usage:

$Bill->alias( 'author' ) ->countOwn( 'book' );

The example above counts all the books associated with 'author' $Bill.

Parameters

string $type

the type of bean you want to count

Returns

integer

countShared()

countShared(string  $type) : integer

Counts all shared beans of type $type.

Also works with via(), with() and withCondition(). Shared beans are beans that have an many-to-many relation. They can be accessed using the sharedXList, where X the type of the shared bean.

Usage:

$book = R::dispense( 'book' ); $book->sharedPageList = R::dispense( 'page', 5 ); R::store( $book ); echo $book->countShared( 'page' );

The code snippet above will output '5', because there are 5 beans of type 'page' in the shared list.

Parameters

string $type

type of bean you wish to count

Returns

integer

aggr()

aggr(string  $list, string  $property, string|NULL  $type = NULL) : array

Iterates through the specified own-list and fetches all properties (with their type) and returns the references.

Use this method to quickly load indirectly related beans in an own-list. Whenever you cannot use a shared-list this method offers the same convenience by aggregating the parent beans of all children in the specified own-list.

Example:

$quest->aggr( 'xownQuestTarget', 'target', 'quest' );

Loads (in batch) and returns references to all quest beans residing in the $questTarget->target properties of each element in the xownQuestTargetList.

Parameters

string $list

the list you wish to process

string $property

the property to load

string|NULL $type

the type of bean residing in this property (optional)

Returns

array

equals()

equals(\RedBeanPHP\OODBBean|null  $bean) : boolean

Tests whether the database identities of two beans are equal.

Two beans are considered 'equal' if:

a. the types of the beans match b. the ids of the beans match

Returns TRUE if the beans are considered equal according to this specification and FALSE otherwise.

Usage:

$coffee->fetchAs( 'flavour' )->taste->equals( R::enum('flavour:mocca') );

The example above compares the flavour label 'mocca' with the flavour label attached to the $coffee bean. This illustrates how to use equals() with RedBeanPHP-style enums.

Parameters

\RedBeanPHP\OODBBean|null $bean

other bean

Returns

boolean

jsonSerialize()

jsonSerialize() 

getSharedList()

getSharedList(string  $type, \RedBeanPHP\OODB  $redbean, \RedBeanPHP\ToolBox  $toolbox) : array

Accesses the shared list of a bean.

To access beans that have been associated with the current bean using a many-to-many relationship use sharedXList where X is the type of beans in the list.

Usage:

$person = R::load( 'person', $id ); $friends = $person->sharedFriendList;

The code snippet above demonstrates how to obtain all beans of type 'friend' that have associated using an N-M relation. This is a private method used by the magic getter / accessor. The example illustrates usage through these accessors.

Parameters

string $type

the name of the list you want to retrieve

\RedBeanPHP\OODB $redbean

instance of the RedBeanPHP OODB class

\RedBeanPHP\ToolBox $toolbox

instance of ToolBox (to get access to core objects)

Returns

array

getOwnList()

getOwnList(string  $type,   $redbean) : array

Accesses the ownList. The 'own' list contains beans associated using a one-to-many relation. The own-lists can be accessed through the magic getter/setter property ownXList where X is the type of beans in that list.

Usage:

$book = R::load( 'book', $id ); $pages = $book->ownPageList;

The example above demonstrates how to access the pages associated with the book. Since this is a private method meant to be used by the magic accessors, the example uses the magic getter instead.

Parameters

string $type

name of the list you want to retrieve

$redbean

Returns

array