\RedBeanPHPR

R-Facade

If you use Composer you don't use the rb.php file which has the R-facade, so here is a separate, namespaced R-facade for those that prefer this.

An alternative option might be to alias RedBeanPHP/Facade.

Summary

Methods
Properties
Constants
setAllowHybridMode()
getVersion()
getDatabaseServerVersion()
testConnection()
setup()
setNarrowFieldMode()
setAllowFluidTransactions()
useISNULLConditions()
transaction()
addDatabase()
createToolbox()
hasDatabase()
selectDatabase()
debug()
fancyDebug()
inspect()
store()
freeze()
loadMulti()
load()
loadForUpdate()
findForUpdate()
findOneForUpdate()
trash()
dispense()
dispenseAll()
findOrDispense()
findOneOrDispense()
find()
findAll()
findAndExport()
findOne()
findLast()
findCollection()
findMulti()
batch()
loadAll()
exec()
getAll()
getCell()
getCursor()
getRow()
getCol()
getAssoc()
getAssocRow()
getInsertID()
dup()
duplicate()
exportAll()
useExportCase()
convertToBeans()
convertToBean()
findFromSQL()
hasTag()
untag()
tag()
addTags()
tagged()
taggedAll()
countTaggedAll()
countTagged()
wipe()
count()
configureFacadeWithToolbox()
begin()
commit()
rollback()
getColumns()
genSlots()
loadJoined()
flat()
nuke()
wipeAll()
storeAll()
trashAll()
trashBatch()
hunt()
useWriterCache()
dispenseLabels()
enum()
gatherLabels()
close()
isoDate()
isoDateTime()
setDatabaseAdapter()
setWriter()
setRedBean()
getDatabaseAdapter()
getPDO()
getDuplicationManager()
getWriter()
getRedBean()
getToolBox()
getExtractedToolbox()
renameAssociation()
beansToArray()
setErrorHandlingFUSE()
dump()
bindFunc()
aliases()
findOrCreate()
findLike()
startLogging()
stopLogging()
getLogs()
resetQueryCount()
getQueryCount()
getLogger()
setAutoResolve()
usePartialBeans()
csv()
matchUp()
getLook()
look()
diff()
addToolBoxWithKey()
removeToolBoxByKey()
getToolBoxByKey()
useJSONFeatures()
children()
countChildren()
countParents()
parents()
noNuke()
camelfy()
uncamelfy()
useFeatureSet()
ext()
__callStatic()
$toolbox
$f
$currentDB
$toolboxes
C_REDBEANPHP_VERSION
No protected methods found
No protected properties found
N/A
query()
$redbean
$writer
$adapter
$associationManager
$tagManager
$duplicationManager
$labelMaker
$finder
$tree
$logger
$plugins
$exportCaseStyle
$allowFluidTransactions
$allowHybridMode
N/A

Constants

C_REDBEANPHP_VERSION

C_REDBEANPHP_VERSION

RedBeanPHP version constant.

Properties

$f

$f : 

Not in use (backward compatibility SQLHelper)

Type

$currentDB

$currentDB : string

Type

string

$toolboxes

$toolboxes : array<mixed,\RedBeanPHP\ToolBox>

Type

array<mixed,\RedBeanPHP\ToolBox>

$plugins

$plugins : array<mixed,callable>

Type

array<mixed,callable>

$exportCaseStyle

$exportCaseStyle : string

Type

string

$allowFluidTransactions

$allowFluidTransactions : boolean

Type

boolean — flag allows transactions through facade in fluid mode

$allowHybridMode

$allowHybridMode : boolean

Type

boolean — flag allows to unfreeze if needed with store(all)

Methods

setAllowHybridMode()

setAllowHybridMode(boolean  $hybrid) : boolean

Sets allow hybrid mode flag. In Hybrid mode (default off), store/storeAll take an extra argument to switch to fluid mode in case of an exception. You can use this to speed up fluid mode. This method returns the previous value of the flag.

Parameters

boolean $hybrid

Returns

boolean

getVersion()

getVersion() : string

Returns the RedBeanPHP version string.

The RedBeanPHP version string always has the same format "X.Y" where X is the major version number and Y is the minor version number. Point releases are not mentioned in the version string.

Returns

string

getDatabaseServerVersion()

getDatabaseServerVersion() : string

Returns the version string from the database server.

Returns

string

testConnection()

testConnection() : boolean

Tests the database connection.

Returns TRUE if connection has been established and FALSE otherwise. Suppresses any warnings that may occur during the testing process and catches all exceptions that might be thrown during the test.

Returns

boolean

setup()

setup(string|\PDO|NULL  $dsn = NULL, string|NULL  $username = NULL, string|NULL  $password = NULL, boolean|array<mixed,string>  $frozen = FALSE, boolean|array<mixed,string>  $partialBeans = FALSE, array  $options = array()) : \RedBeanPHP\ToolBox

Kickstarts redbean for you. This method should be called before you start using RedBeanPHP. The Setup() method can be called without any arguments, in this case it will try to create a SQLite database in /tmp called red.db (this only works on UNIX-like systems).

Usage:

R::setup( 'mysql:host=localhost;dbname=mydatabase', 'dba', 'dbapassword' );

You can replace 'mysql:' with the name of the database you want to use. Possible values are:

  • pgsql (PostgreSQL database)
  • sqlite (SQLite database)
  • mysql (MySQL database)
  • mysql (also for Maria database)
  • sqlsrv (MS SQL Server - community supported experimental driver)
  • CUBRID (CUBRID driver - basic support provided by Plugin)

Note that setup() will not immediately establish a connection to the database. Instead, it will prepare the connection and connect 'lazily', i.e. the moment a connection is really required, for instance when attempting to load a bean.

Parameters

string|\PDO|NULL $dsn

Database connection string

string|NULL $username

Username for database

string|NULL $password

Password for database

boolean|array<mixed,string> $frozen

TRUE if you want to setup in frozen mode

boolean|array<mixed,string> $partialBeans

TRUE to enable partial bean updates

array $options

Additional (PDO) options to pass

Returns

\RedBeanPHP\ToolBox

setNarrowFieldMode()

setNarrowFieldMode(  $mode) : void

Toggles 'Narrow Field Mode'.

In Narrow Field mode the queryRecord method will narrow its selection field to

SELECT {table}.*

instead of

SELECT *

This is a better way of querying because it allows more flexibility (for instance joins). However if you need the wide selector for backward compatibility; use this method to turn OFF Narrow Field Mode by passing FALSE. Default is TRUE.

Parameters

$mode

setAllowFluidTransactions()

setAllowFluidTransactions(boolean  $mode) : void

Toggles fluid transactions. By default fluid transactions are not active. Starting, committing or rolling back a transaction through the facade in fluid mode will have no effect. If you wish to replace this standard portable behavior with behavior depending on how the used database platform handles fluid (DDL) transactions set this flag to TRUE.

Parameters

boolean $mode

allow fluid transaction mode

useISNULLConditions()

useISNULLConditions(  $mode) : boolean

Toggles support for IS-NULL-conditions.

If IS-NULL-conditions are enabled condition arrays for functions including findLike() are treated so that 'field' => NULL will be interpreted as field IS NULL instead of being skipped. Returns the previous value of the flag.

Parameters

$mode

Returns

boolean

transaction()

transaction(callable  $callback) : mixed

Wraps a transaction around a closure or string callback.

If an Exception is thrown inside, the operation is automatically rolled back. If no Exception happens, it commits automatically. It also supports (simulated) nested transactions (that is useful when you have many methods that needs transactions but are unaware of each other).

Example:

$from = 1; $to = 2; $amount = 300;

R::transaction(function() use($from, $to, $amount) { $accountFrom = R::load('account', $from); $accountTo = R::load('account', $to); $accountFrom->money -= $amount; $accountTo->money += $amount; R::store($accountFrom); R::store($accountTo); });

Parameters

callable $callback

Closure (or other callable) with the transaction logic

Returns

mixed

addDatabase()

addDatabase(string  $key, string|\PDO  $dsn, string|NULL  $user = NULL, string|NULL  $pass = NULL, boolean|array<mixed,string>  $frozen = FALSE, boolean|array<mixed,string>  $partialBeans = FALSE, array  $options = array(), \RedBeanPHP\BeanHelper|NULL  $beanHelper = NULL) : void

Adds a database to the facade, afterwards you can select the database using selectDatabase($key), where $key is the name you assigned to this database.

Usage:

R::addDatabase( 'database-1', 'sqlite:/tmp/db1.txt' ); R::selectDatabase( 'database-1' ); //to select database again

This method allows you to dynamically add (and select) new databases to the facade. Adding a database with the same key will cause an exception.

Parameters

string $key

ID for the database

string|\PDO $dsn

DSN for the database

string|NULL $user

user for connection

string|NULL $pass

password for connection

boolean|array<mixed,string> $frozen

whether this database is frozen or not

boolean|array<mixed,string> $partialBeans

should we load partial beans?

array $options

additional options for the query writer

\RedBeanPHP\BeanHelper|NULL $beanHelper

Beanhelper to use (use this for DB specific model prefixes)

createToolbox()

createToolbox(string|\PDO  $dsn, string  $username = NULL, string  $password = NULL, boolean|array<mixed,string>  $frozen = FALSE, boolean|array<mixed,string>  $partialBeans = FALSE, array  $options = array()) : \RedBeanPHP\ToolBox

Creates a toolbox. This method can be called if you want to use redbean non-static.

It has the same interface as R::setup(). The createToolbox() method can be called without any arguments, in this case it will try to create a SQLite database in /tmp called red.db (this only works on UNIX-like systems).

Usage:

R::createToolbox( 'mysql:host=localhost;dbname=mydatabase', 'dba', 'dbapassword' );

You can replace 'mysql:' with the name of the database you want to use. Possible values are:

  • pgsql (PostgreSQL database)
  • sqlite (SQLite database)
  • mysql (MySQL database)
  • mysql (also for Maria database)
  • sqlsrv (MS SQL Server - community supported experimental driver)
  • CUBRID (CUBRID driver - basic support provided by Plugin)

Note that createToolbox() will not immediately establish a connection to the database. Instead, it will prepare the connection and connect 'lazily', i.e. the moment a connection is really required, for instance when attempting to load a bean.

Parameters

string|\PDO $dsn

Database connection string

string $username

Username for database

string $password

Password for database

boolean|array<mixed,string> $frozen

TRUE if you want to setup in frozen mode

boolean|array<mixed,string> $partialBeans

TRUE to enable partial bean updates

array $options

Returns

\RedBeanPHP\ToolBox

hasDatabase()

hasDatabase(string  $key) : boolean

Determines whether a database identified with the specified key has already been added to the facade. This function will return TRUE if the database indicated by the key is available and FALSE otherwise.

Parameters

string $key

the key/name of the database to check for

Returns

boolean

selectDatabase()

selectDatabase(string  $key, boolean  $force = FALSE) : boolean

Selects a different database for the Facade to work with.

If you use the R::setup() you don't need this method. This method is meant for multiple database setups. This method selects the database identified by the database ID ($key). Use addDatabase() to add a new database, which in turn can be selected using selectDatabase(). If you use R::setup(), the resulting database will be stored under key 'default', to switch (back) to this database use R::selectDatabase( 'default' ). This method returns TRUE if the database has been switched and FALSE otherwise (for instance if you already using the specified database).

Parameters

string $key

Key of the database to select

boolean $force

Returns

boolean

debug()

debug(boolean  $tf = TRUE, integer  $mode) : \RedBeanPHP\Logger\RDefault

Toggles DEBUG mode.

In Debug mode all SQL that happens under the hood will be printed to the screen and/or logged. If no database connection has been configured using R::setup() or R::selectDatabase() this method will throw an exception.

There are 2 debug styles:

Classic: separate parameter bindings, explicit and complete but less readable Fancy: interspersed bindings, truncates large strings, highlighted schema changes

Fancy style is more readable but sometimes incomplete.

The first parameter turns debugging ON or OFF. The second parameter indicates the mode of operation:

0 Log and write to STDOUT classic style (default) 1 Log only, class style 2 Log and write to STDOUT fancy style 3 Log only, fancy style

This function always returns the logger instance created to generate the debug messages.

Parameters

boolean $tf

debug mode (TRUE or FALSE)

integer $mode

mode of operation

Throws

\RedBeanPHP\RedException

Returns

\RedBeanPHP\Logger\RDefault

fancyDebug()

fancyDebug(boolean  $toggle = TRUE) : void

Turns on the fancy debugger.

In 'fancy' mode the debugger will output queries with bound parameters inside the SQL itself. This method has been added to offer a convenient way to activate the fancy debugger system in one call.

Parameters

boolean $toggle

TRUE to activate debugger and select 'fancy' mode

inspect()

inspect(string|NULL  $type = NULL) : array<mixed,string>

Inspects the database schema. If you pass the type of a bean this method will return the fields of its table in the database.

The keys of this array will be the field names and the values will be the column types used to store their values. If no type is passed, this method returns a list of all tables in the database.

Parameters

string|NULL $type

Type of bean (i.e. table) you want to inspect, or NULL for a list of all tables

Returns

array<mixed,string>

store()

store(\RedBeanPHP\OODBBean|\RedBeanPHP\SimpleModel  $bean, boolean  $unfreezeIfNeeded = FALSE) : integer|string

Stores a bean in the database. This method takes a OODBBean Bean Object $bean and stores it in the database. If the database schema is not compatible with this bean and RedBean runs in fluid mode the schema will be altered to store the bean correctly.

If the database schema is not compatible with this bean and RedBean runs in frozen mode it will throw an exception. This function returns the primary key ID of the inserted bean.

The return value is an integer if possible. If it is not possible to represent the value as an integer a string will be returned.

Usage:

$post = R::dispense('post'); $post->title = 'my post'; $id = R::store( $post ); $post = R::load( 'post', $id ); R::trash( $post );

In the example above, we create a new bean of type 'post'. We then set the title of the bean to 'my post' and we store the bean. The store() method will return the primary key ID $id assigned by the database. We can now use this ID to load the bean from the database again and delete it.

If the second parameter is set to TRUE and Hybrid mode is allowed (default OFF for novice), then RedBeanPHP will automatically temporarily switch to fluid mode to attempt to store the bean in case of an SQLException.

Parameters

\RedBeanPHP\OODBBean|\RedBeanPHP\SimpleModel $bean

bean to store

boolean $unfreezeIfNeeded

retries in fluid mode in hybrid mode

Returns

integer|string

freeze()

freeze(boolean|array<mixed,string>  $tf = TRUE) : void

Toggles fluid or frozen mode. In fluid mode the database structure is adjusted to accommodate your objects. In frozen mode this is not the case.

You can also pass an array containing a selection of frozen types. Let's call this chilly mode, it's just like fluid mode except that certain types (i.e. tables) aren't touched.

Parameters

boolean|array<mixed,string> $tf

mode of operation (TRUE means frozen)

loadMulti()

loadMulti(string|array<mixed,string>  $types, integer  $id) : array<mixed,\RedBeanPHP\OODBBean>

Loads multiple types of beans with the same ID.

This might look like a strange method, however it can be useful for loading a one-to-one relation. In a typical 1-1 relation, you have two records sharing the same primary key. RedBeanPHP has only limited support for 1-1 relations. In general it is recommended to use 1-N for this.

Usage:

list( $author, $bio ) = R::loadMulti( 'author, bio', $id );

Parameters

string|array<mixed,string> $types

the set of types to load at once

integer $id

the common ID

Returns

array<mixed,\RedBeanPHP\OODBBean>

load()

load(string  $type, integer  $id, string|NULL  $snippet = NULL) : \RedBeanPHP\OODBBean

Loads a bean from the object database.

It searches for a OODBBean Bean Object in the database. It does not matter how this bean has been stored. RedBean uses the primary key ID $id and the string $type to find the bean. The $type specifies what kind of bean you are looking for; this is the same type as used with the dispense() function. If RedBean finds the bean it will return the OODB Bean object; if it cannot find the bean RedBean will return a new bean of type $type and with primary key ID 0. In the latter case it acts basically the same as dispense().

Important note: If the bean cannot be found in the database a new bean of the specified type will be generated and returned.

Usage:

$post = R::dispense('post'); $post->title = 'my post'; $id = R::store( $post ); $post = R::load( 'post', $id ); R::trash( $post );

In the example above, we create a new bean of type 'post'. We then set the title of the bean to 'my post' and we store the bean. The store() method will return the primary key ID $id assigned by the database. We can now use this ID to load the bean from the database again and delete it.

Parameters

string $type

type of bean you want to load

integer $id

ID of the bean you want to load

string|NULL $snippet

string to use after select (optional)

Returns

\RedBeanPHP\OODBBean

loadForUpdate()

loadForUpdate(string  $type, integer  $id) : \RedBeanPHP\OODBBean

Same as load, but selects the bean for update, thus locking the bean.

This equals an SQL query like 'SELECT ... FROM ... FOR UPDATE'. Use this method if you want to load a bean you intend to UPDATE. This method should be used to 'LOCK a bean'.

Usage:

$bean = R::loadForUpdate( 'bean', $id ); ...update... R::store( $bean );

Parameters

string $type

type of bean you want to load

integer $id

ID of the bean you want to load

Returns

\RedBeanPHP\OODBBean

findForUpdate()

findForUpdate(string  $type, string|NULL  $sql = NULL, array  $bindings = array()) : array<mixed,\RedBeanPHP\OODBBean>

Same as find(), but selects the beans for update, thus locking the beans.

This equals an SQL query like 'SELECT ... FROM ... FOR UPDATE'. Use this method if you want to load a bean you intend to UPDATE. This method should be used to 'LOCK a bean'.

Usage:

$bean = R::findForUpdate( 'bean', ' title LIKE ? ', array('title') ); ...update... R::store( $bean );

Parameters

string $type

the type of bean you are looking for

string|NULL $sql

SQL query to find the desired bean, starting right after WHERE clause

array $bindings

array of values to be bound to parameters in query

Returns

array<mixed,\RedBeanPHP\OODBBean>

findOneForUpdate()

findOneForUpdate(string  $type, string|NULL  $sql = NULL, array  $bindings = array()) : \RedBeanPHP\OODBBean|NULL

Convenience method.

Same as findForUpdate but returns just one bean and adds LIMIT-clause.

Parameters

string $type

the type of bean you are looking for

string|NULL $sql

SQL query to find the desired bean, starting right after WHERE clause

array $bindings

array of values to be bound to parameters in query

Returns

\RedBeanPHP\OODBBean|NULL

trash()

trash(string|\RedBeanPHP\OODBBean|\RedBeanPHP\SimpleModel  $beanOrType, integer  $id = NULL) : integer

Removes a bean from the database.

This function will remove the specified OODBBean Bean Object from the database.

This facade method also accepts a type-id combination, in the latter case this method will attempt to load the specified bean and THEN trash it.

Usage:

$post = R::dispense('post'); $post->title = 'my post'; $id = R::store( $post ); $post = R::load( 'post', $id ); R::trash( $post );

In the example above, we create a new bean of type 'post'. We then set the title of the bean to 'my post' and we store the bean. The store() method will return the primary key ID $id assigned by the database. We can now use this ID to load the bean from the database again and delete it.

Parameters

string|\RedBeanPHP\OODBBean|\RedBeanPHP\SimpleModel $beanOrType

bean you want to remove from database

integer $id

ID if the bean to trash (optional, type-id variant only)

Returns

integer

dispense()

dispense(string|array<mixed,\RedBeanPHP\OODBBean>  $typeOrBeanArray, integer  $num = 1, boolean  $alwaysReturnArray = FALSE) : \RedBeanPHP\OODBBean|array<mixed,\RedBeanPHP\OODBBean>

Dispenses a new RedBean OODB Bean for use with the rest of the methods. RedBeanPHP thinks in beans, the bean is the primary way to interact with RedBeanPHP and the database managed by RedBeanPHP. To load, store and delete data from the database using RedBeanPHP you exchange these RedBeanPHP OODB Beans. The only exception to this rule are the raw query methods like R::getCell() or R::exec() and so on.

The dispense method is the 'preferred way' to create a new bean.

Usage:

$book = R::dispense( 'book' ); $book->title = 'My Book'; R::store( $book );

This method can also be used to create an entire bean graph at once. Given an array with keys specifying the property names of the beans and a special _type key to indicate the type of bean, one can make the Dispense Helper generate an entire hierarchy of beans, including lists. To make dispense() generate a list, simply add a key like: ownXList or sharedXList where X is the type of beans it contains and a set its value to an array filled with arrays representing the beans. Note that, although the type may have been hinted at in the list name, you still have to specify a _type key for every bean array in the list. Note that, if you specify an array to generate a bean graph, the number parameter will be ignored.

Usage:

$book = R::dispense( [ '_type' => 'book', 'title' => 'Gifted Programmers', 'author' => [ '_type' => 'author', 'name' => 'Xavier' ], 'ownPageList' => [ ['_type'=>'page', 'text' => '...'] ] ] );

Parameters

string|array<mixed,\RedBeanPHP\OODBBean> $typeOrBeanArray

type or bean array to import

integer $num

number of beans to dispense

boolean $alwaysReturnArray

if TRUE always returns the result as an array

Returns

\RedBeanPHP\OODBBean|array<mixed,\RedBeanPHP\OODBBean>

dispenseAll()

dispenseAll(string  $order, boolean  $onlyArrays = FALSE) : array

Takes a comma separated list of bean types and dispenses these beans. For each type in the list you can specify the number of beans to be dispensed.

Usage:

list( $book, $page, $text ) = R::dispenseAll( 'book,page,text' );

This will dispense a book, a page and a text. This way you can quickly dispense beans of various types in just one line of code.

Usage:

list($book, $pages) = R::dispenseAll('book,page*100');

This returns an array with a book bean and then another array containing 100 page beans.

Parameters

string $order

a description of the desired dispense order using the syntax above

boolean $onlyArrays

return only arrays even if amount < 2

Returns

array

findOrDispense()

findOrDispense(string  $type, string|NULL  $sql = NULL, array  $bindings = array()) : array<mixed,\RedBeanPHP\OODBBean>

Convenience method. Tries to find beans of a certain type, if no beans are found, it dispenses a bean of that type.

Note that this function always returns an array.

Parameters

string $type

type of bean you are looking for

string|NULL $sql

SQL code for finding the bean

array $bindings

parameters to bind to SQL

Returns

array<mixed,\RedBeanPHP\OODBBean>

findOneOrDispense()

findOneOrDispense(string  $type, string|NULL  $sql = NULL, array  $bindings = array()) : \RedBeanPHP\OODBBean

Same as findOrDispense but returns just one element.

Parameters

string $type

type of bean you are looking for

string|NULL $sql

SQL code for finding the bean

array $bindings

parameters to bind to SQL

Returns

\RedBeanPHP\OODBBean

find()

find(string  $type, string|NULL  $sql = NULL, array  $bindings = array(), string|NULL  $snippet = NULL) : array<mixed,\RedBeanPHP\OODBBean>

Finds beans using a type and optional SQL statement.

As with most Query tools in RedBean you can provide values to be inserted in the SQL statement by populating the value array parameter; you can either use the question mark notation or the slot-notation (:keyname).

Your SQL does not have to start with a WHERE-clause condition.

Parameters

string $type

the type of bean you are looking for

string|NULL $sql

SQL query to find the desired bean, starting right after WHERE clause

array $bindings

array of values to be bound to parameters in query

string|NULL $snippet

SQL snippet to include in query (for example: FOR UPDATE)

Returns

array<mixed,\RedBeanPHP\OODBBean>

findAll()

findAll(string  $type, string|NULL  $sql = NULL, array  $bindings = array()) : array<mixed,\RedBeanPHP\OODBBean>

Alias for find().

Parameters

string $type

the type of bean you are looking for

string|NULL $sql

SQL query to find the desired bean, starting right after WHERE clause

array $bindings

array of values to be bound to parameters in query

Returns

array<mixed,\RedBeanPHP\OODBBean>

findAndExport()

findAndExport(string  $type, string|NULL  $sql = NULL, array  $bindings = array()) : array

Like find() but also exports the beans as an array.

This method will perform a find-operation. For every bean in the result collection this method will call the export() method. This method returns an array containing the array representations of every bean in the result set.

Parameters

string $type

type the type of bean you are looking for

string|NULL $sql

sql SQL query to find the desired bean, starting right after WHERE clause

array $bindings

values array of values to be bound to parameters in query

Returns

array

findOne()

findOne(string  $type, string|NULL  $sql = NULL, array  $bindings = array()) : \RedBeanPHP\OODBBean|NULL

Like R::find() but returns the first bean only.

Parameters

string $type

the type of bean you are looking for

string|NULL $sql

SQL query to find the desired bean, starting right after WHERE clause

array $bindings

array of values to be bound to parameters in query

Returns

\RedBeanPHP\OODBBean|NULL

findLast()

findLast(string  $type, string|NULL  $sql = NULL, array  $bindings = array()) : \RedBeanPHP\OODBBean|NULL

Parameters

string $type

the type of bean you are looking for

string|NULL $sql

SQL query to find the desired bean, starting right after WHERE clause

array $bindings

values array of values to be bound to parameters in query

Returns

\RedBeanPHP\OODBBean|NULL

findCollection()

findCollection(string  $type, string|NULL  $sql = NULL, array  $bindings = array()) : \RedBeanPHP\BeanCollection

Finds a BeanCollection using the repository.

A bean collection can be used to retrieve one bean at a time using cursors - this is useful for processing large datasets. A bean collection will not load all beans into memory all at once, just one at a time.

Parameters

string $type

the type of bean you are looking for

string|NULL $sql

SQL query to find the desired bean, starting right after WHERE clause

array $bindings

values array of values to be bound to parameters in query

Returns

\RedBeanPHP\BeanCollection

findMulti()

findMulti(string|array<mixed,string>  $types, string|array<mixed,array>|NULL  $sql, array  $bindings = array(), array<mixed,array>  $remappings = array()) : array

Returns a hashmap with bean arrays keyed by type using an SQL query as its resource. Given an SQL query like 'SELECT movie.*, review.* FROM movie.

.. JOIN review' this method will return movie and review beans.

Example:

$stuff = $finder->findMulti('movie,review', ' SELECT movie., review. FROM movie LEFT JOIN review ON review.movie_id = movie.id');

After this operation, $stuff will contain an entry 'movie' containing all movies and an entry named 'review' containing all reviews (all beans). You can also pass bindings.

If you want to re-map your beans, so you can use $movie->ownReviewList without having RedBeanPHP executing an SQL query you can use the fourth parameter to define a selection of remapping closures.

The remapping argument (optional) should contain an array of arrays. Each array in the remapping array should contain the following entries:

array( 'a' => TYPE A 'b' => TYPE B 'matcher' => MATCHING FUNCTION ACCEPTING A, B and ALL BEANS 'do' => OPERATION FUNCTION ACCEPTING A, B, ALL BEANS, ALL REMAPPINGS )

Using this mechanism you can build your own 'preloader' with tiny function snippets (and those can be re-used and shared online of course).

Example:

array( 'a' => 'movie' //define A as movie 'b' => 'review' //define B as review 'matcher' => function( $a, $b ) { return ( $b->movie_id == $a->id ); //Perform action if review.movie_id equals movie.id } 'do' => function( $a, $b ) { $a->noLoad()->ownReviewList[] = $b; //Add the review to the movie $a->clearHistory(); //optional, act 'as if these beans have been loaded through ownReviewList'. } )

Parameters

string|array<mixed,string> $types

a list of types (either array or comma separated string)

string|array<mixed,array>|NULL $sql

an SQL query or an array of prefetched records

array $bindings

optional, bindings for SQL query

array<mixed,array> $remappings

optional, an array of remapping arrays

Returns

array

batch()

batch(string  $type, array<mixed,integer>  $ids) : array<mixed,\RedBeanPHP\OODBBean>

Returns an array of beans. Pass a type and a series of ids and this method will bring you the corresponding beans.

important note: Because this method loads beans using the load() function (but faster) it will return empty beans with ID 0 for every bean that could not be located. The resulting beans will have the passed IDs as their keys.

Parameters

string $type

type of beans

array<mixed,integer> $ids

ids to load

Returns

array<mixed,\RedBeanPHP\OODBBean>

loadAll()

loadAll(string  $type, array<mixed,integer>  $ids) : array<mixed,\RedBeanPHP\OODBBean>

Alias for batch(). Batch method is older but since we added so-called *All methods like storeAll, trashAll, dispenseAll and findAll it seemed logical to improve the consistency of the Facade API and also add an alias for batch() called loadAll.

Parameters

string $type

type of beans

array<mixed,integer> $ids

ids to load

Returns

array<mixed,\RedBeanPHP\OODBBean>

exec()

exec(string  $sql, array  $bindings = array()) : integer

Convenience function to execute Queries directly.

Executes SQL.

Parameters

string $sql

SQL query to execute

array $bindings

a list of values to be bound to query parameters

Returns

integer

getAll()

getAll(string  $sql, array  $bindings = array()) : array<mixed,string[]>

Convenience function to fire an SQL query using the RedBeanPHP database adapter. This method allows you to directly query the database without having to obtain an database adapter instance first.

Executes the specified SQL query together with the specified parameter bindings and returns all rows and all columns.

Parameters

string $sql

SQL query to execute

array $bindings

a list of values to be bound to query parameters

Returns

array<mixed,string[]>

getCell()

getCell(string  $sql, array  $bindings = array()) : string|NULL

Convenience function to fire an SQL query using the RedBeanPHP database adapter. This method allows you to directly query the database without having to obtain an database adapter instance first.

Executes the specified SQL query together with the specified parameter bindings and returns a single cell.

Parameters

string $sql

SQL query to execute

array $bindings

a list of values to be bound to query parameters

Returns

string|NULL

getCursor()

getCursor(string  $sql, array  $bindings = array()) : \RedBeanPHP\Cursor

Convenience function to fire an SQL query using the RedBeanPHP database adapter. This method allows you to directly query the database without having to obtain an database adapter instance first.

Executes the specified SQL query together with the specified parameter bindings and returns a PDOCursor instance.

Parameters

string $sql

SQL query to execute

array $bindings

a list of values to be bound to query parameters

Returns

\RedBeanPHP\Cursor

getRow()

getRow(string  $sql, array  $bindings = array()) : array|NULL

Convenience function to fire an SQL query using the RedBeanPHP database adapter. This method allows you to directly query the database without having to obtain an database adapter instance first.

Executes the specified SQL query together with the specified parameter bindings and returns a single row.

Parameters

string $sql

SQL query to execute

array $bindings

a list of values to be bound to query parameters

Returns

array|NULL

getCol()

getCol(string  $sql, array  $bindings = array()) : array<mixed,string>

Convenience function to fire an SQL query using the RedBeanPHP database adapter. This method allows you to directly query the database without having to obtain an database adapter instance first.

Executes the specified SQL query together with the specified parameter bindings and returns a single column.

Parameters

string $sql

SQL query to execute

array $bindings

a list of values to be bound to query parameters

Returns

array<mixed,string>

getAssoc()

getAssoc(string  $sql, array  $bindings = array()) : array<mixed,string>

Convenience function to execute Queries directly.

Executes SQL. Results will be returned as an associative array. The first column in the select clause will be used for the keys in this array and the second column will be used for the values. If only one column is selected in the query, both key and value of the array will have the value of this field for each row.

Parameters

string $sql

SQL query to execute

array $bindings

a list of values to be bound to query parameters

Returns

array<mixed,string>

getAssocRow()

getAssocRow(string  $sql, array  $bindings = array()) : array

Convenience function to fire an SQL query using the RedBeanPHP database adapter. This method allows you to directly query the database without having to obtain an database adapter instance first.

Executes the specified SQL query together with the specified parameter bindings and returns an associative array. Results will be returned as an associative array indexed by the first column in the select.

Parameters

string $sql

SQL query to execute

array $bindings

a list of values to be bound to query parameters

Returns

array

getInsertID()

getInsertID() : integer

Returns the insert ID for databases that support/require this functionality. Alias for R::getAdapter()->getInsertID().

Returns

integer

dup()

dup(\RedBeanPHP\OODBBean  $bean, array<mixed,\RedBeanPHP\OODBBean>  $trail = array(), boolean  $pid = FALSE, array  $filters = array()) : \RedBeanPHP\OODBBean

Makes a copy of a bean. This method makes a deep copy of the bean.The copy will have the following features.

  • All beans in own-lists will be duplicated as well
  • All references to shared beans will be copied but not the shared beans themselves
  • All references to parent objects (_id fields) will be copied but not the parents themselves In most cases this is the desired scenario for copying beans. This function uses a trail-array to prevent infinite recursion, if a recursive bean is found (i.e. one that already has been processed) the ID of the bean will be returned. This should not happen though.

Note: This function does a reflectional database query so it may be slow.

Parameters

\RedBeanPHP\OODBBean $bean

bean to be copied

array<mixed,\RedBeanPHP\OODBBean> $trail

for internal usage, pass array()

boolean $pid

for internal usage

array $filters

white list filter with bean types to duplicate

Returns

\RedBeanPHP\OODBBean

duplicate()

duplicate(\RedBeanPHP\OODBBean  $bean, array  $filters = array()) : \RedBeanPHP\OODBBean

Makes a deep copy of a bean. This method makes a deep copy of the bean.The copy will have the following:

  • All beans in own-lists will be duplicated as well
  • All references to shared beans will be copied but not the shared beans themselves
  • All references to parent objects (_id fields) will be copied but not the parents themselves

In most cases this is the desired scenario for copying beans. This function uses a trail-array to prevent infinite recursion, if a recursive bean is found (i.e. one that already has been processed) the ID of the bean will be returned. This should not happen though.

Note: This function does a reflectional database query so it may be slow.

Note: This is a simplified version of the deprecated R::dup() function.

Parameters

\RedBeanPHP\OODBBean $bean

bean to be copied

array $filters

white list filter with bean types to duplicate

Returns

\RedBeanPHP\OODBBean

exportAll()

exportAll(\RedBeanPHP\OODBBean|array<mixed,\RedBeanPHP\OODBBean>  $beans, boolean  $parents = FALSE, array  $filters = array(), boolean  $meta = FALSE) : array<mixed,array>

Exports a collection of beans. Handy for XML/JSON exports with a Javascript framework like Dojo or ExtJS.

What will be exported:

  • contents of the bean
  • all own bean lists (recursively)
  • all shared beans (not THEIR own lists)

Parameters

\RedBeanPHP\OODBBean|array<mixed,\RedBeanPHP\OODBBean> $beans

beans to be exported

boolean $parents

whether you want parent beans to be exported

array $filters

whitelist of types

boolean $meta

export meta data as well

Returns

array<mixed,array>

useExportCase()

useExportCase(string  $caseStyle = 'default') : void

Selects case style for export.

This will determine the case style for the keys of exported beans (see exportAll). The following options are accepted:

  • 'default' RedBeanPHP by default enforces Snake Case (i.e. book_id is_valid )
  • 'camel' Camel Case (i.e. bookId isValid )
  • 'dolphin' Dolphin Case (i.e. bookID isValid ) Like CamelCase but ID is written all uppercase

Parameters

string $caseStyle

case style identifier

convertToBeans()

convertToBeans(string  $type, array<mixed,string[]>  $rows, string|array|NULL  $metamask = NULL) : array<mixed,\RedBeanPHP\OODBBean>

Converts a series of rows to beans.

This method converts a series of rows to beans. The type of the desired output beans can be specified in the first parameter. The second parameter is meant for the database result rows.

Usage:

$rows = R::getAll( 'SELECT * FROM ...' ) $beans = R::convertToBeans( $rows );

As of version 4.3.2 you can specify a meta-mask. Data from columns with names starting with the value specified in the mask will be transferred to the meta section of a bean (under data.bundle).

$rows = R::getAll( 'SELECT FROM... COUNT(*) AS extracount ...' ); $beans = R::convertToBeans( $rows, 'extra' ); $bean = reset( $beans ); $data = $bean->getMeta( 'data.bundle' ); $extra_count = $data['extra_count'];

New in 4.3.2: meta mask. The meta mask is a special mask to send data from raw result rows to the meta store of the bean. This is useful for bundling additional information with custom queries. Values of every column who's name starts with $mask will be transferred to the meta section of the bean under key 'data.bundle'.

Parameters

string $type

type of beans to produce

array<mixed,string[]> $rows

must contain an array of array

string|array|NULL $metamask

meta mask to apply (optional)

Returns

array<mixed,\RedBeanPHP\OODBBean>

convertToBean()

convertToBean(string  $type, array<mixed,string>  $row, string|array|NULL  $metamask = NULL) : \RedBeanPHP\OODBBean|NULL

Just like convertToBeans, but for one bean.

Parameters

string $type

type of bean to produce

array<mixed,string> $row

one row from the database

string|array|NULL $metamask

metamask (see convertToBeans)

Returns

\RedBeanPHP\OODBBean|NULL

findFromSQL()

findFromSQL(string  $type, string  $sql, array  $bindings = array(), string|array  $metamask = 'extra_', boolean  $autoExtract = false) : array

Convenience function to 'find' beans from an SQL query.

Used mostly to obtain a series of beans as well as pagination data (to paginate results) and optionally other data as well (that should not be considered part of a bean).

Example:

$books = R::findFromSQL('book'," SELECT , count() OVER() AS total FROM book WHERE {$filter} OFFSET {$from} LIMIT {$to} ", ['total']);

This is the same as doing (example uses PostgreSQL dialect):

$rows = R::getAll(" SELECT , count() OVER() AS total FROM book WHERE {$filter} OFFSET {$from} LIMIT {$to} ", $params); $books = R::convertToBeans('book', $rows, ['total']);

The additional data can be obtained using:

$book->info('total');

For further details see R::convertToBeans(). If you set $autoExtract to TRUE and meta mask is an array, an array will be returned containing two nested arrays, the first of those nested arrays will contain the meta values you requested, the second array will contain the beans.

Parameters

string $type

Type of bean to produce

string $sql

SQL query snippet to use

array $bindings

bindings for query (optional)

string|array $metamask

meta mask (optional, defaults to 'extra_')

boolean $autoExtract

TRUE to return meta mask values as first item of array

Returns

array

hasTag()

hasTag(\RedBeanPHP\OODBBean  $bean, string|array<mixed,string>  $tags, boolean  $all = FALSE) : boolean

Tests whether a bean has been associated with one ore more of the listed tags. If the third parameter is TRUE this method will return TRUE only if all tags that have been specified are indeed associated with the given bean, otherwise FALSE.

If the third parameter is FALSE this method will return TRUE if one of the tags matches, FALSE if none match.

Tag list can be either an array with tag names or a comma separated list of tag names.

Usage:

R::hasTag( $blog, 'horror,movie', TRUE );

The example above returns TRUE if the $blog bean has been tagged as BOTH horror and movie. If the post has only been tagged as 'movie' or 'horror' this operation will return FALSE because the third parameter has been set to TRUE.

Parameters

\RedBeanPHP\OODBBean $bean

bean to check for tags

string|array<mixed,string> $tags

list of tags

boolean $all

whether they must all match or just some

Returns

boolean

untag()

untag(\RedBeanPHP\OODBBean  $bean, string|array<mixed,string>  $tagList) : void

Removes all specified tags from the bean. The tags specified in the second parameter will no longer be associated with the bean.

Tag list can be either an array with tag names or a comma separated list of tag names.

Usage:

R::untag( $blog, 'smart,interesting' );

In the example above, the $blog bean will no longer be associated with the tags 'smart' and 'interesting'.

Parameters

\RedBeanPHP\OODBBean $bean

tagged bean

string|array<mixed,string> $tagList

list of tags (names)

tag()

tag(\RedBeanPHP\OODBBean  $bean, array<mixed,string>|NULL  $tagList = NULL) : array<mixed,string>

Tags a bean or returns tags associated with a bean.

If $tagList is NULL or omitted this method will return a comma separated list of tags associated with the bean provided. If $tagList is a comma separated list (string) of tags all tags will be associated with the bean. You may also pass an array instead of a string.

Usage:

R::tag( $meal, "TexMex,Mexican" ); $tags = R::tag( $meal );

The first line in the example above will tag the $meal as 'TexMex' and 'Mexican Cuisine'. The second line will retrieve all tags attached to the meal object.

Parameters

\RedBeanPHP\OODBBean $bean

bean to tag

array<mixed,string>|NULL $tagList

tags to attach to the specified bean

Returns

array<mixed,string>

addTags()

addTags(\RedBeanPHP\OODBBean  $bean, string|array<mixed,string>  $tagList) : void

Adds tags to a bean.

If $tagList is a comma separated list of tags all tags will be associated with the bean. You may also pass an array instead of a string.

Usage:

R::addTags( $blog, ["halloween"] );

The example adds the tag 'halloween' to the $blog bean.

Parameters

\RedBeanPHP\OODBBean $bean

bean to tag

string|array<mixed,string> $tagList

list of tags to add to bean

tagged()

tagged(string  $beanType, string|array<mixed,string>  $tagList, string  $sql = '', array  $bindings = array()) : array<mixed,\RedBeanPHP\OODBBean>

Returns all beans that have been tagged with one or more of the specified tags.

Tag list can be either an array with tag names or a comma separated list of tag names.

Usage:

$watchList = R::tagged( 'movie', 'horror,gothic', ' ORDER BY movie.title DESC LIMIT ?', [ 10 ] );

The example uses R::tagged() to find all movies that have been tagged as 'horror' or 'gothic', order them by title and limit the number of movies to be returned to 10.

Parameters

string $beanType

type of bean you are looking for

string|array<mixed,string> $tagList

list of tags to match

string $sql

additional SQL (use only for pagination)

array $bindings

bindings

Returns

array<mixed,\RedBeanPHP\OODBBean>

taggedAll()

taggedAll(string  $beanType, string|array<mixed,string>  $tagList, string  $sql = '', array  $bindings = array()) : array<mixed,\RedBeanPHP\OODBBean>

Returns all beans that have been tagged with ALL of the tags given.

This method works the same as R::tagged() except that this method only returns beans that have been tagged with all the specified labels.

Tag list can be either an array with tag names or a comma separated list of tag names.

Usage:

$watchList = R::taggedAll( 'movie', [ 'gothic', 'short' ], ' ORDER BY movie.id DESC LIMIT ? ', [ 4 ] );

The example above returns at most 4 movies (due to the LIMIT clause in the SQL Query Snippet) that have been tagged as BOTH 'short' AND 'gothic'.

Parameters

string $beanType

type of bean you are looking for

string|array<mixed,string> $tagList

list of tags to match

string $sql

additional sql snippet

array $bindings

bindings

Returns

array<mixed,\RedBeanPHP\OODBBean>

countTaggedAll()

countTaggedAll(string  $beanType, string|array<mixed,string>  $tagList, string  $sql = '', array  $bindings = array()) : integer

Same as taggedAll() but counts beans only (does not return beans).

Parameters

string $beanType

type of bean you are looking for

string|array<mixed,string> $tagList

list of tags to match

string $sql

additional sql snippet

array $bindings

bindings

Returns

integer

countTagged()

countTagged(string  $beanType, string|array<mixed,string>  $tagList, string  $sql = '', array  $bindings = array()) : integer

Same as tagged() but counts beans only (does not return beans).

Parameters

string $beanType

type of bean you are looking for

string|array<mixed,string> $tagList

list of tags to match

string $sql

additional sql snippet

array $bindings

bindings

Returns

integer

wipe()

wipe(string  $beanType) : boolean

Wipes all beans of type $beanType.

Parameters

string $beanType

type of bean you want to destroy entirely

Returns

boolean

count()

count(string  $type, string  $addSQL = '', array  $bindings = array()) : integer

Counts the number of beans of type $type.

This method accepts a second argument to modify the count-query. A third argument can be used to provide bindings for the SQL snippet.

Parameters

string $type

type of bean we are looking for

string $addSQL

additional SQL snippet

array $bindings

parameters to bind to SQL

Returns

integer

configureFacadeWithToolbox()

configureFacadeWithToolbox(\RedBeanPHP\ToolBox  $tb) : \RedBeanPHP\ToolBox

Configures the facade, want to have a new Writer? A new Object Database or a new Adapter and you want it on-the-fly? Use this method to hot-swap your facade with a new toolbox.

Parameters

\RedBeanPHP\ToolBox $tb

toolbox to configure facade with

Returns

\RedBeanPHP\ToolBox

begin()

begin() : boolean

Facade Convenience method for adapter transaction system.

Begins a transaction.

Usage:

R::begin(); try { $bean1 = R::dispense( 'bean' ); R::store( $bean1 ); $bean2 = R::dispense( 'bean' ); R::store( $bean2 ); R::commit(); } catch( \Exception $e ) { R::rollback(); }

The example above illustrates how transactions in RedBeanPHP are used. In this example 2 beans are stored or nothing is stored at all. It's not possible for this piece of code to store only half of the beans. If an exception occurs, the transaction gets rolled back and the database will be left 'untouched'.

In fluid mode transactions will be ignored and all queries will be executed as-is because database schema changes will automatically trigger the transaction system to commit everything in some database systems. If you use a database that can handle DDL changes you might wish to use setAllowFluidTransactions(TRUE). If you do this, the behavior of this function in fluid mode will depend on the database platform used.

Returns

boolean

commit()

commit() : boolean

Facade Convenience method for adapter transaction system.

Commits a transaction.

Usage:

R::begin(); try { $bean1 = R::dispense( 'bean' ); R::store( $bean1 ); $bean2 = R::dispense( 'bean' ); R::store( $bean2 ); R::commit(); } catch( \Exception $e ) { R::rollback(); }

The example above illustrates how transactions in RedBeanPHP are used. In this example 2 beans are stored or nothing is stored at all. It's not possible for this piece of code to store only half of the beans. If an exception occurs, the transaction gets rolled back and the database will be left 'untouched'.

In fluid mode transactions will be ignored and all queries will be executed as-is because database schema changes will automatically trigger the transaction system to commit everything in some database systems. If you use a database that can handle DDL changes you might wish to use setAllowFluidTransactions(TRUE). If you do this, the behavior of this function in fluid mode will depend on the database platform used.

Returns

boolean

rollback()

rollback() : boolean

Facade Convenience method for adapter transaction system.

Rolls back a transaction.

Usage:

R::begin(); try { $bean1 = R::dispense( 'bean' ); R::store( $bean1 ); $bean2 = R::dispense( 'bean' ); R::store( $bean2 ); R::commit(); } catch( \Exception $e ) { R::rollback(); }

The example above illustrates how transactions in RedBeanPHP are used. In this example 2 beans are stored or nothing is stored at all. It's not possible for this piece of code to store only half of the beans. If an exception occurs, the transaction gets rolled back and the database will be left 'untouched'.

In fluid mode transactions will be ignored and all queries will be executed as-is because database schema changes will automatically trigger the transaction system to commit everything in some database systems. If you use a database that can handle DDL changes you might wish to use setAllowFluidTransactions(TRUE). If you do this, the behavior of this function in fluid mode will depend on the database platform used.

Returns

boolean

getColumns()

getColumns(string  $table) : array<mixed,string>

Returns a list of columns. Format of this array: array( fieldname => type ) Note that this method only works in fluid mode because it might be quite heavy on production servers!

Parameters

string $table

name of the table (not type) you want to get columns of

Returns

array<mixed,string>

genSlots()

genSlots(array  $array, string|NULL  $template = NULL) : string

Generates question mark slots for an array of values.

Given an array and an optional template string this method will produce string containing parameter slots for use in an SQL query string.

Usage:

R::genSlots( array( 'a', 'b' ) );

The statement in the example will produce the string: '?,?'.

Another example, using a template string:

R::genSlots( array('a', 'b'), ' IN( %s ) ' );

The statement in the example will produce the string: ' IN( ?,? ) '.

Parameters

array $array

array to generate question mark slots for

string|NULL $template

template to use

Returns

string

loadJoined()

loadJoined(array<mixed,\RedBeanPHP\OODBBean>  $beans, string  $type, string  $sqlTemplate = 'SELECT %s.* FROM %s WHERE id IN (%s)') : array<mixed,\RedBeanPHP\OODBBean>

Convenience method to quickly attach parent beans.

Although usually this can also be done with findMulti(), that approach can be a bit verbose sometimes. This convenience method uses a default yet overridable SQL snippet to perform the operation, leveraging the power of findMulti().

Usage:

$users = R::find('user'); $users = R::loadJoined( $users, 'country' );

This is an alternative for:

$all = R::findMulti('country', R::genSlots( $users, 'SELECT country.* FROM country WHERE id IN ( %s )' ), array_column( $users, 'country_id' ), [Finder::onmap('country', $gebruikers)] );

Parameters

array<mixed,\RedBeanPHP\OODBBean> $beans

a list of OODBBeans

string $type

a type string

string $sqlTemplate

an SQL template string for the SELECT-query

Returns

array<mixed,\RedBeanPHP\OODBBean>

flat()

flat(array  $array, array  $result = array()) : array

Flattens a multi dimensional bindings array for use with genSlots().

Usage:

R::flat( array( 'a', array( 'b' ), 'c' ) );

produces an array like: [ 'a', 'b', 'c' ]

Parameters

array $array

array to flatten

array $result

result array parameter (for recursion)

Returns

array

nuke()

nuke() : void

Nukes the entire database.

This will remove all schema structures from the database. Only works in fluid mode. Be careful with this method.

wipeAll()

wipeAll(boolean  $alsoDeleteTables = FALSE) : void

Truncates or drops all database tables/views.

Empties the database. If the deleteTables flag is set to TRUE this function will also remove the database structures. The latter only works in fluid mode.

Parameters

boolean $alsoDeleteTables

TRUE to clear entire database.

storeAll()

storeAll(array<mixed,\RedBeanPHP\OODBBean>  $beans, boolean  $unfreezeIfNeeded = FALSE) : array<mixed,integer>

Short hand function to store a set of beans at once, IDs will be returned as an array. For information please consult the R::store() function.

A loop saver.

If the second parameter is set to TRUE and Hybrid mode is allowed (default OFF for novice), then RedBeanPHP will automatically temporarily switch to fluid mode to attempt to store the bean in case of an SQLException.

Parameters

array<mixed,\RedBeanPHP\OODBBean> $beans

list of beans to be stored

boolean $unfreezeIfNeeded

retries in fluid mode in hybrid mode

Returns

array<mixed,integer> —

ids

trashAll()

trashAll(array<mixed,\RedBeanPHP\OODBBean>  $beans) : integer

Short hand function to trash a set of beans at once.

For information please consult the R::trash() function. A loop saver.

Parameters

array<mixed,\RedBeanPHP\OODBBean> $beans

list of beans to be trashed

Returns

integer

trashBatch()

trashBatch(string  $type, array<mixed,integer>  $ids) : void

Short hand function to trash a series of beans using only IDs. This function combines trashAll and batch loading in one call. Note that while this function accepts just bean IDs, the beans will still be loaded first. This is because the function still respects all the FUSE hooks that may have been associated with the domain logic associated with these beans.

If you really want to delete just records from the database use a simple DELETE-FROM SQL query instead.

Parameters

string $type

the bean type you wish to trash

array<mixed,integer> $ids

list of bean IDs

hunt()

hunt(string  $type, string|NULL  $sqlSnippet = NULL, array  $bindings = array()) : integer

Short hand function to find and trash beans.

This function combines trashAll and find. Given a bean type, a query snippet and optionally some parameter bindings, this function will search for the beans described in the query and its parameters and then feed them to the trashAll function to be trashed.

Note that while this function accepts just a bean type and query snippet, the beans will still be loaded first. This is because the function still respects all the FUSE hooks that may have been associated with the domain logic associated with these beans. If you really want to delete just records from the database use a simple DELETE-FROM SQL query instead.

Returns the number of beans deleted.

Parameters

string $type

bean type to look for in database

string|NULL $sqlSnippet

an SQL query snippet

array $bindings

SQL parameter bindings

Returns

integer

useWriterCache()

useWriterCache(boolean  $yesNo) : void

Toggles Writer Cache.

Turns the Writer Cache on or off. The Writer Cache is a simple query based caching system that may improve performance without the need for cache management. This caching system will cache non-modifying queries that are marked with special SQL comments. As soon as a non-marked query gets executed the cache will be flushed. Only non-modifying select queries have been marked therefore this mechanism is a rather safe way of caching, requiring no explicit flushes or reloads. Of course this does not apply if you intend to test or simulate concurrent querying.

Parameters

boolean $yesNo

TRUE to enable cache, FALSE to disable cache

dispenseLabels()

dispenseLabels(string  $type, array<mixed,string>  $labels) : array<mixed,\RedBeanPHP\OODBBean>

A label is a bean with only an id, type and name property.

This function will dispense beans for all entries in the array. The values of the array will be assigned to the name property of each individual bean.

Parameters

string $type

type of beans you would like to have

array<mixed,string> $labels

list of labels, names for each bean

Returns

array<mixed,\RedBeanPHP\OODBBean>

enum()

enum(string  $enum) : \RedBeanPHP\OODBBean|array<mixed,\RedBeanPHP\OODBBean>

Generates and returns an ENUM value. This is how RedBeanPHP handles ENUMs.

Either returns a (newly created) bean representing the desired ENUM value or returns a list of all enums for the type.

To obtain (and add if necessary) an ENUM value:

$tea->flavour = R::enum( 'flavour:apple' );

Returns a bean of type 'flavour' with name = apple. This will add a bean with property name (set to APPLE) to the database if it does not exist yet.

To obtain all flavours:

R::enum('flavour');

To get a list of all flavour names:

R::gatherLabels( R::enum( 'flavour' ) );

Parameters

string $enum

either type or type-value

Returns

\RedBeanPHP\OODBBean|array<mixed,\RedBeanPHP\OODBBean>

gatherLabels()

gatherLabels(array<mixed,\RedBeanPHP\OODBBean>  $beans) : array<mixed,string>

Gathers labels from beans. This function loops through the beans, collects the values of the name properties of each individual bean and stores the names in a new array. The array then gets sorted using the default sort function of PHP (sort).

Parameters

array<mixed,\RedBeanPHP\OODBBean> $beans

list of beans to loop

Returns

array<mixed,string>

close()

close() : void

Closes the database connection.

While database connections are closed automatically at the end of the PHP script, closing database connections is generally recommended to improve performance. Closing a database connection will immediately return the resources to PHP.

Usage:

R::setup( ... ); ... do stuff ... R::close();

isoDate()

isoDate(integer|NULL  $time = NULL) : string

Simple convenience function, returns ISO date formatted representation of $time.

Parameters

integer|NULL $time

UNIX timestamp

Returns

string

isoDateTime()

isoDateTime(integer|NULL  $time = NULL) : string

Simple convenience function, returns ISO date time formatted representation of $time.

Parameters

integer|NULL $time

UNIX timestamp

Returns

string

setDatabaseAdapter()

setDatabaseAdapter(\RedBeanPHP\Adapter  $adapter) : void

Sets the database adapter you want to use.

The database adapter manages the connection to the database and abstracts away database driver specific interfaces.

Parameters

\RedBeanPHP\Adapter $adapter

Database Adapter for facade to use

setWriter()

setWriter(\RedBeanPHP\QueryWriter  $writer) : void

Sets the Query Writer you want to use.

The Query Writer writes and executes database queries using the database adapter. It turns RedBeanPHP 'commands' into database 'statements'.

Parameters

\RedBeanPHP\QueryWriter $writer

Query Writer instance for facade to use

setRedBean()

setRedBean(\RedBeanPHP\OODB  $redbean) 

Sets the OODB you want to use.

The RedBeanPHP Object oriented database is the main RedBeanPHP interface that allows you to store and retrieve RedBeanPHP objects (i.e. beans).

Parameters

\RedBeanPHP\OODB $redbean

Object Database for facade to use

getDatabaseAdapter()

getDatabaseAdapter() : \RedBeanPHP\Adapter

Optional accessor for neat code.

Sets the database adapter you want to use.

Returns

\RedBeanPHP\Adapter

getPDO()

getPDO() : NULL|\PDO

In case you use PDO (which is recommended and the default but not mandatory, hence the database adapter), you can use this method to obtain the PDO object directly.

This is a convenience method, it will do the same as:

R::getDatabaseAdapter()->getDatabase()->getPDO();

If the PDO object could not be found, for whatever reason, this method will return NULL instead.

Returns

NULL|\PDO

getDuplicationManager()

getDuplicationManager() : \RedBeanPHP\DuplicationManager

Returns the current duplication manager instance.

Returns

\RedBeanPHP\DuplicationManager

getWriter()

getWriter() : \RedBeanPHP\QueryWriter

Optional accessor for neat code.

Sets the database adapter you want to use.

Returns

\RedBeanPHP\QueryWriter

getRedBean()

getRedBean() : \RedBeanPHP\OODB

Optional accessor for neat code.

Sets the database adapter you want to use.

Returns

\RedBeanPHP\OODB

getToolBox()

getToolBox() : \RedBeanPHP\ToolBox

Returns the toolbox currently used by the facade.

To set the toolbox use R::setup() or R::configureFacadeWithToolbox(). To create a toolbox use Setup::kickstart(). Or create a manual toolbox using the ToolBox class.

Returns

\RedBeanPHP\ToolBox

getExtractedToolbox()

getExtractedToolbox() : array

Mostly for internal use, but might be handy for some users.

This returns all the components of the currently selected toolbox.

Returns the components in the following order:

OODB instance (getRedBean())

Database Adapter

Query Writer

Toolbox itself

Returns

array

renameAssociation()

renameAssociation(string|array<mixed,string>  $from, string  $to = NULL) : void

Facade method for AQueryWriter::renameAssociation()

Parameters

string|array<mixed,string> $from
string $to

beansToArray()

beansToArray(array<mixed,\RedBeanPHP\OODBBean>  $beans) : array<mixed,array>

Little helper method for Resty Bean Can server and others.

Takes an array of beans and exports each bean. Unlike exportAll this method does not recurse into own lists and shared lists, the beans are exported as-is, only loaded lists are exported.

Parameters

array<mixed,\RedBeanPHP\OODBBean> $beans

beans

Returns

array<mixed,array>

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

mode, determines how to handle errors

callable|NULL $func

custom handler (if applicable)

Returns

array

dump()

dump(\RedBeanPHP\OODBBean|array<mixed,\RedBeanPHP\OODBBean>  $data) : string|array<mixed,string>

Dumps bean data to array.

Given a one or more beans this method will return an array containing first part of the string representation of each item in the array.

Usage:

echo R::dump( $bean );

The example shows how to echo the result of a simple dump. This will print the string representation of the specified bean to the screen, limiting the output per bean to 35 characters to improve readability. Nested beans will also be dumped.

Parameters

\RedBeanPHP\OODBBean|array<mixed,\RedBeanPHP\OODBBean> $data

either a bean or an array of beans

Returns

string|array<mixed,string>

bindFunc()

bindFunc(string  $mode, string  $field, string  $function, boolean  $isTemplate = FALSE) : void

Binds an SQL function to a column.

This method can be used to setup a decode/encode scheme or perform UUID insertion. This method is especially useful for handling MySQL spatial columns, because they need to be processed first using the asText/GeomFromText functions.

Example:

R::bindFunc( 'read', 'location.point', 'asText' ); R::bindFunc( 'write', 'location.point', 'GeomFromText' );

Passing NULL as the function will reset (clear) the function for this column/mode.

Parameters

string $mode

mode for function: i.e. read or write

string $field

field (table.column) to bind function to

string $function

SQL function to bind to specified column

boolean $isTemplate

TRUE if $function is an SQL string, FALSE for just a function name

aliases()

aliases(array<mixed,string>  $list) : void

Sets global aliases.

Registers a batch of aliases in one go. This works the same as fetchAs 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.

Parameters

array<mixed,string> $list

list of global aliases to use

findOrCreate()

findOrCreate(string  $type, array  $like = array(),   $sql = '',   $hasBeenCreated = false) : \RedBeanPHP\OODBBean

Tries to find a bean matching a certain type and criteria set. If no beans are found a new bean will be created, the criteria will be imported into this bean and the bean will be stored and returned.

If multiple beans match the criteria only the first one will be returned.

Parameters

string $type

type of bean to search for

array $like

criteria set describing the bean to search for

$sql
$hasBeenCreated

Returns

\RedBeanPHP\OODBBean

findLike()

findLike(string  $type, array  $like = array(), string  $sql = '', array  $bindings = array()) : array<mixed,\RedBeanPHP\OODBBean>

Tries to find beans matching the specified type and criteria set.

If the optional additional SQL snippet is a condition, it will be glued to the rest of the query using the AND operator.

Parameters

string $type

type of bean to search for

array $like

optional criteria set describing the bean to search for

string $sql

optional additional SQL for sorting

array $bindings

bindings

Returns

array<mixed,\RedBeanPHP\OODBBean>

startLogging()

startLogging() : void

Starts logging queries.

Use this method to start logging SQL queries being executed by the adapter. Logging queries will not print them on the screen. Use R::getLogs() to retrieve the logs.

Usage:

R::startLogging(); R::store( R::dispense( 'book' ) ); R::find('book', 'id > ?',[0]); $logs = R::getLogs(); $count = count( $logs ); print_r( $logs ); R::stopLogging();

In the example above we start a logging session during which we store an empty bean of type book. To inspect the logs we invoke R::getLogs() after stopping the logging.

stopLogging()

stopLogging() : void

Stops logging and flushes the logs, convenient method to stop logging of queries.

Use this method to stop logging SQL queries being executed by the adapter. Logging queries will not print them on the screen. Use R::getLogs() to retrieve the logs.

R::startLogging(); R::store( R::dispense( 'book' ) ); R::find('book', 'id > ?',[0]); $logs = R::getLogs(); $count = count( $logs ); print_r( $logs ); R::stopLogging();

In the example above we start a logging session during which we store an empty bean of type book. To inspect the logs we invoke R::getLogs() after stopping the logging.

getLogs()

getLogs() : array<mixed,string>

Returns the log entries written after the startLogging.

Use this method to obtain the query logs gathered by the logging mechanisms. Logging queries will not print them on the screen. Use R::getLogs() to retrieve the logs.

R::startLogging(); R::store( R::dispense( 'book' ) ); R::find('book', 'id > ?',[0]); $logs = R::getLogs(); $count = count( $logs ); print_r( $logs ); R::stopLogging();

In the example above we start a logging session during which we store an empty bean of type book. To inspect the logs we invoke R::getLogs() after stopping the logging.

The logs may look like:

[1] => SELECT book.* FROM book WHERE id > ? -- keep-cache [2] => array ( 0 => 0, ) [3] => resultset: 1 rows

Basically, element in the array is a log entry. Parameter bindings are represented as nested arrays (see 2).

Returns

array<mixed,string>

resetQueryCount()

resetQueryCount() : void

Resets the query counter.

The query counter can be used to monitor the number of database queries that have been processed according to the database driver. You can use this to monitor the number of queries required to render a page.

Usage:

R::resetQueryCount(); echo R::getQueryCount() . ' queries processed.';

getQueryCount()

getQueryCount() : integer

Returns the number of SQL queries processed.

This method returns the number of database queries that have been processed according to the database driver. You can use this to monitor the number of queries required to render a page.

Usage:

echo R::getQueryCount() . ' queries processed.';

Returns

integer

getLogger()

getLogger() : \RedBeanPHP\Logger|NULL

Returns the current logger instance being used by the database object.

Returns

\RedBeanPHP\Logger|NULL

setAutoResolve()

setAutoResolve(  $automatic = TRUE) 

Parameters

$automatic

usePartialBeans()

usePartialBeans(boolean|array<mixed,string>  $yesNoBeans) : boolean|array<mixed,string>

Toggles 'partial bean mode'. If this mode has been selected the repository will only update the fields of a bean that have been changed rather than the entire bean.

Pass the value TRUE to select 'partial mode' for all beans. Pass the value FALSE to disable 'partial mode'. Pass an array of bean types if you wish to use partial mode only for some types. This method will return the previous value.

Parameters

boolean|array<mixed,string> $yesNoBeans

List of type names or 'all'

Returns

boolean|array<mixed,string>

csv()

csv(string  $sql = '', array  $bindings = array(), array  $columns = NULL, string  $path = '/tmp/redexport_%s.csv', boolean  $output = TRUE) : void

Exposes the result of the specified SQL query as a CSV file.

Usage:

R::csv( 'SELECT name, population FROM city WHERE region = :region ', array( ':region' => 'Denmark' ), array( 'city', 'population' ), '/tmp/cities.csv' );

The command above will select all cities in Denmark and create a CSV with columns 'city' and 'population' and populate the cells under these column headers with the names of the cities and the population numbers respectively.

Parameters

string $sql

SQL query to expose result of

array $bindings

parameter bindings

array $columns

column headers for CSV file

string $path

path to save CSV file to

boolean $output

TRUE to output CSV directly using readfile

matchUp()

matchUp(string  $type, string  $sql, array  $bindings = array(), array  $onFoundDo = NULL, array  $onNotFoundDo = NULL,   $bean = NULL) : boolean|NULL

MatchUp is a powerful productivity boosting method that can replace simple control scripts with a single RedBeanPHP command. Typically, matchUp() is used to replace login scripts, token generation scripts and password reset scripts.

The MatchUp method takes a bean type, an SQL query snippet (starting at the WHERE clause), SQL bindings, a pair of task arrays and a bean reference.

If the first 3 parameters match a bean, the first task list will be considered, otherwise the second one will be considered. On consideration, each task list, an array of keys and values will be executed. Every key in the task list should correspond to a bean property while every value can either be an expression to be evaluated or a closure (PHP 5.3+). After applying the task list to the bean it will be stored. If no bean has been found, a new bean will be dispensed.

This method will return TRUE if the bean was found and FALSE if not AND there was a NOT-FOUND task list. If no bean was found AND there was also no second task list, NULL will be returned.

To obtain the bean, pass a variable as the sixth parameter. The function will put the matching bean in the specified variable.

Parameters

string $type

type of bean you're looking for

string $sql

SQL snippet (starting at the WHERE clause, omit WHERE-keyword)

array $bindings

array of parameter bindings for SQL snippet

array $onFoundDo

task list to be considered on finding the bean

array $onNotFoundDo

task list to be considered on NOT finding the bean

$bean

Returns

boolean|NULL

look()

look(string  $sql, array  $bindings = array(), array  $keys = array('selected', 'id', 'name'), string  $template = '<option %s value="%s">%s</option>', callable  $filter = 'trim', string  $glue = '') : string

Takes an full SQL query with optional bindings, a series of keys, a template and optionally a filter function and glue and assembles a view from all this.

This is the fastest way from SQL to view. Typically this function is used to generate pulldown (select tag) menus with options queried from the database.

Usage:

$htmlPulldown = R::look( 'SELECT * FROM color WHERE value != ? ORDER BY value ASC', [ 'g' ], [ 'value', 'name' ], '', 'strtoupper', "\n" );

The example above creates an HTML fragment like this:

to pick a color from a palette. The HTML fragment gets constructed by an SQL query that selects all colors that do not have value 'g' - this excludes green. Next, the bean properties 'value' and 'name' are mapped to the HTML template string, note that the order here is important. The mapping and the HTML template string follow vsprintf-rules. All property values are then passed through the specified filter function 'strtoupper' which in this case is a native PHP function to convert strings to uppercase characters only. Finally the resulting HTML fragment strings are glued together using a newline character specified in the last parameter for readability.

In previous versions of RedBeanPHP you had to use: R::getLook()->look() instead of R::look(). However to improve useability of the library the look() function can now directly be invoked from the facade.

Parameters

string $sql

query to execute

array $bindings

parameters to bind to slots mentioned in query or an empty array

array $keys

names in result collection to map to template

string $template

HTML template to fill with values associated with keys, use printf notation (i.e. %s)

callable $filter

function to pass values through (for translation for instance)

string $glue

optional glue to use when joining resulting strings

Returns

string

diff()

diff(\RedBeanPHP\OODBBean|array<mixed,\RedBeanPHP\OODBBean>  $bean, \RedBeanPHP\OODBBean|array<mixed,\RedBeanPHP\OODBBean>  $other, array  $filters = array('created', 'modified'), string  $pattern = '%s.%s.%s') : array

Calculates a diff between two beans (or arrays of beans).

The result of this method is an array describing the differences of the second bean compared to the first, where the first bean is taken as reference. The array is keyed by type/property, id and property name, where type/property is either the type (in case of the root bean) or the property of the parent bean where the type resides. The diffs are mainly intended for logging, you cannot apply these diffs as patches to other beans. However this functionality might be added in the future.

The keys of the array can be formatted using the $format parameter. A key will be composed of a path (1st), id (2nd) and property (3rd). Using printf-style notation you can determine the exact format of the key. The default format will look like:

'book.1.title' => array( , )

If you only want a simple diff of one bean and you don't care about ids, you might pass a format like: '%1$s.%3$s' which gives:

'book.1.title' => array( , )

The filter parameter can be used to set filters, it should be an array of property names that have to be skipped. By default this array is filled with two strings: 'created' and 'modified'.

Parameters

\RedBeanPHP\OODBBean|array<mixed,\RedBeanPHP\OODBBean> $bean

reference beans

\RedBeanPHP\OODBBean|array<mixed,\RedBeanPHP\OODBBean> $other

beans to compare

array $filters

names of properties of all beans to skip

string $pattern

the format of the key, defaults to '%s.%s.%s'

Returns

array

addToolBoxWithKey()

addToolBoxWithKey(string  $key, \RedBeanPHP\ToolBox  $toolbox) : void

The gentleman's way to register a RedBeanPHP ToolBox instance with the facade. Stores the toolbox in the static toolbox registry of the facade class. This allows for a neat and explicit way to register a toolbox.

Parameters

string $key

key to store toolbox instance under

\RedBeanPHP\ToolBox $toolbox

toolbox to register

removeToolBoxByKey()

removeToolBoxByKey(string  $key) : boolean

The gentleman's way to remove a RedBeanPHP ToolBox instance from the facade. Removes the toolbox identified by the specified key in the static toolbox registry of the facade class. This allows for a neat and explicit way to remove a toolbox.

Returns TRUE if the specified toolbox was found and removed. Returns FALSE otherwise.

Parameters

string $key

identifier of the toolbox to remove

Returns

boolean

getToolBoxByKey()

getToolBoxByKey(string  $key) : \RedBeanPHP\ToolBox|NULL

Returns the toolbox associated with the specified key.

Parameters

string $key

key to store toolbox instance under

Returns

\RedBeanPHP\ToolBox|NULL

useJSONFeatures()

useJSONFeatures(boolean  $flag) : void

Toggles JSON column features.

Invoking this method with boolean TRUE causes 2 JSON features to be enabled. Beans will automatically JSONify any array that's not in a list property and the Query Writer (if capable) will attempt to create a JSON column for strings that appear to contain JSON.

Feature #1: AQueryWriter::useJSONColumns

Toggles support for automatic generation of JSON columns. Using JSON columns means that strings containing JSON will cause the column to be created (not modified) as a JSON column. However it might also trigger exceptions if this means the DB attempts to convert a non-json column to a JSON column.

Feature #2: OODBBean::convertArraysToJSON

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.

So invoking this method is the same as:

AQueryWriter::useJSONColumns( $flag ); OODBBean::convertArraysToJSON( $flag );

Unlike the methods above, that return the previous state, this method does not return anything (void).

Parameters

boolean $flag

feature flag (either TRUE or FALSE)

children()

children(\RedBeanPHP\OODBBean  $bean, string|NULL  $sql = NULL, array  $bindings = array()) : array<mixed,\RedBeanPHP\OODBBean>

Given a bean and an optional SQL snippet, this method will return the bean together with all child beans in a hierarchically structured bean table.

Parameters

\RedBeanPHP\OODBBean $bean

bean to find children of

string|NULL $sql

optional SQL snippet

array $bindings

SQL snippet parameter bindings

Returns

array<mixed,\RedBeanPHP\OODBBean>

countChildren()

countChildren(\RedBeanPHP\OODBBean  $bean, string|NULL  $sql = NULL, array  $bindings = array(), string|boolean  $select = \RedBeanPHP\QueryWriter::C_CTE_SELECT_COUNT) : integer

Given a bean and an optional SQL snippet, this method will count all child beans in a hierarchically structured bean table.

Parameters

\RedBeanPHP\OODBBean $bean

bean to find children of

string|NULL $sql

optional SQL snippet

array $bindings

SQL snippet parameter bindings

string|boolean $select

select snippet to use (advanced, optional, see QueryWriter::queryRecursiveCommonTableExpression)

Returns

integer

countParents()

countParents(\RedBeanPHP\OODBBean  $bean, string|NULL  $sql = NULL, array  $bindings = array(), string|boolean  $select = \RedBeanPHP\QueryWriter::C_CTE_SELECT_COUNT) : integer

Given a bean and an optional SQL snippet, this method will count all parent beans in a hierarchically structured bean table.

Parameters

\RedBeanPHP\OODBBean $bean

bean to find children of

string|NULL $sql

optional SQL snippet

array $bindings

SQL snippet parameter bindings

string|boolean $select

select snippet to use (advanced, optional, see QueryWriter::queryRecursiveCommonTableExpression)

Returns

integer

parents()

parents(\RedBeanPHP\OODBBean  $bean, string|NULL  $sql = NULL, array  $bindings = array()) : array<mixed,\RedBeanPHP\OODBBean>

Given a bean and an optional SQL snippet, this method will return the bean along with all parent beans in a hierarchically structured bean table.

Parameters

\RedBeanPHP\OODBBean $bean

bean to find parents of

string|NULL $sql

optional SQL snippet

array $bindings

SQL snippet parameter bindings

Returns

array<mixed,\RedBeanPHP\OODBBean>

noNuke()

noNuke(  $yesNo) : boolean

Toggles support for nuke().

Can be used to turn off the nuke() feature for security reasons. Returns the old flag value.

Parameters

$yesNo

Returns

boolean

camelfy()

camelfy(string|array  $snake, boolean  $dolphin = false) : string|array

Globally available service method for RedBeanPHP.

Converts a snake cased string to a camel cased string. If the parameter is an array, the keys will be converted.

Parameters

string|array $snake

snake_cased string to convert to camelCase

boolean $dolphin

exception for Ids - (bookId -> bookID) too complicated for the human mind, only dolphins can understand this

Returns

string|array

uncamelfy()

uncamelfy(string|array  $camel) : string|array

Globally available service method for RedBeanPHP.

Converts a camel cased string to a snake cased string. If the parameter is an array, the keys will be converted.

Parameters

string|array $camel

camelCased string to convert to snake case

Returns

string|array

useFeatureSet()

useFeatureSet(string  $label) : void

Selects the feature set you want as specified by the label.

Usage:

R::useFeatureSet( 'novice/latest' );

Parameters

string $label

label

ext()

ext(string  $pluginName, callable  $callable) : void

Dynamically extends the facade with a plugin.

Using this method you can register your plugin with the facade and then use the plugin by invoking the name specified plugin name as a method on the facade.

Usage:

R::ext( 'makeTea', function() { ... } );

Now you can use your makeTea plugin like this:

R::makeTea();

Parameters

string $pluginName

name of the method to call the plugin

callable $callable

a PHP callable

__callStatic()

__callStatic(string  $pluginName, array  $params) : mixed

Call static for use with dynamic plugins. This magic method will intercept static calls and route them to the specified plugin.

Parameters

string $pluginName

name of the plugin

array $params

list of arguments to pass to plugin method

Returns

mixed

query()

query(string  $method, string  $sql, array  $bindings) : array|integer|\RedBeanPHP\Cursor|NULL

Internal Query function, executes the desired query. Used by all facade query functions. This keeps things DRY.

Parameters

string $method

desired query method (i.e. 'cell', 'col', 'exec' etc..)

string $sql

the sql you want to execute

array $bindings

array of values to be bound to query statement

Returns

array|integer|\RedBeanPHP\Cursor|NULL