\RedBeanPHPFacade

RedBean Facade

Version Information RedBean Version @version 5.2

This class hides the object landscape of RedBeanPHP behind a single letter class providing almost all functionality with simple static calls.

Summary

Methods
Properties
Constants
getVersion()
testConnection()
setup()
setNarrowFieldMode()
transaction()
addDatabase()
hasDatabase()
selectDatabase()
debug()
fancyDebug()
inspect()
store()
freeze()
loadMulti()
load()
loadForUpdate()
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()
hasTag()
untag()
tag()
addTags()
tagged()
taggedAll()
wipe()
count()
configureFacadeWithToolbox()
begin()
commit()
rollback()
getColumns()
genSlots()
flat()
nuke()
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()
parents()
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
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

Type

array

$plugins

$plugins : array

Type

array

$exportCaseStyle

$exportCaseStyle : string

Type

string

Methods

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

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  $dsn = NULL, string  $username = NULL, string  $password = NULL, boolean  $frozen = FALSE,   $partialBeans = FALSE) : \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 $dsn

Database connection string

string $username

Username for database

string $password

Password for database

boolean $frozen

TRUE if you want to setup in frozen mode

$partialBeans

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

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  $dsn, string  $user = NULL, NULL|string  $pass = NULL, boolean  $frozen = FALSE,   $partialBeans = FALSE) : 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 $dsn

DSN for the database

string $user

user for connection

NULL|string $pass

password for connection

boolean $frozen

whether this database is frozen or not

$partialBeans

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,   $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

$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: interpersed 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  $type = NULL) : array

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 $type

Type of bean (i.e. table) you want to inspect

Returns

array

store()

store(\RedBeanPHP\OODBBean|\RedBeanPHP\SimpleModel  $bean) : 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.

Parameters

\RedBeanPHP\OODBBean|\RedBeanPHP\SimpleModel $bean

bean to store

Returns

integer|string

freeze()

freeze(boolean|array  $tf = TRUE) 

Toggles fluid or frozen mode. In fluid mode the database structure is adjusted to accomodate 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 $tf

mode of operation (TRUE means frozen)

loadMulti()

loadMulti(string|array  $types, mixed  $id) : \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 $types

the set of types to load at once

mixed $id

the common ID

Returns

\RedBeanPHP\OODBBean

load()

load(string  $type, integer  $id, string  $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 $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

trash()

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

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)

dispense()

dispense(string|array  $typeOrBeanArray, integer  $num = 1, boolean  $alwaysReturnArray = FALSE) : array|\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 $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

array|\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  $sql = NULL, array  $bindings = array()) : array

Convience 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 $sql

SQL code for finding the bean

array $bindings

parameters to bind to SQL

Returns

array

findOneOrDispense()

findOneOrDispense(string  $type, string  $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 $sql

SQL code for finding the bean

array $bindings

parameters to bind to SQL

Returns

\RedBeanPHP\OODBBean

find()

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

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 $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

findAll()

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

Alias for find().

Parameters

string $type

the type of bean you are looking for

string $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

findAndExport()

findAndExport(string  $type, string  $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 $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  $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 $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  $sql = NULL, array  $bindings = array()) : \RedBeanPHP\OODBBean|NULL

Parameters

string $type

the type of bean you are looking for

string $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  $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 $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  $types, string|array  $sql, array  $bindings = array(), 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 $types

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

string|array $sql

an SQL query or an array of prefetched records

array $bindings

optional, bindings for SQL query

array $remappings

optional, an array of remapping arrays

Returns

array

batch()

batch(string  $type, array  $ids) : array

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 $ids

ids to load

Returns

array

loadAll()

loadAll(string  $type, array  $ids) : array

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 $ids

ids to load

Returns

array

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

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

getCell()

getCell(string  $sql, array  $bindings = array()) : 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 cell.

Parameters

string $sql

SQL query to execute

array $bindings

a list of values to be bound to query parameters

Returns

string

getCursor()

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

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\RedBeanPHP\Cursor\PDOCursor

getRow()

getRow(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 a single row.

Parameters

string $sql

SQL query to execute

array $bindings

a list of values to be bound to query parameters

Returns

array

getCol()

getCol(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 a single column.

Parameters

string $sql

SQL query to execute

array $bindings

a list of values to be bound to query parameters

Returns

array

getAssoc()

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

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

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() : mixed

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

Returns

mixed

dup()

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

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 $trail

for internal usage, pass array()

boolean $pid

for internal usage

array $filters

white list filter with bean types to duplicate

Returns

array

duplicate()

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

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

$filters

Returns

array

exportAll()

exportAll(array|\RedBeanPHP\OODBBean  $beans, boolean  $parents = FALSE, array  $filters = array()) : 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

array|\RedBeanPHP\OODBBean $beans

beans to be exported

boolean $parents

whether you want parent beans to be exported

array $filters

whitelist of types

Returns

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  $rows, string  $metamask = NULL) : array

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 extra_count ...' ); $beans = R::convertToBeans( $rows ); $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 whos 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 $rows

must contain an array of array

string $metamask

meta mask to apply (optional)

Returns

array

convertToBean()

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

Just like converToBeans, but for one bean.

Parameters

string $type

type of bean to produce

array $row

one row from the database

string $metamask

metamask (see convertToBeans)

Returns

\RedBeanPHP\RedBeanPHP\OODBBean

hasTag()

hasTag(\RedBeanPHP\OODBBean  $bean, array|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

array|string $tags

list of tags

boolean $all

whether they must all match or just some

Returns

boolean

untag()

untag(\RedBeanPHP\OODBBean  $bean, array  $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

array $tagList

list of tags (names)

tag()

tag(\RedBeanPHP\OODBBean  $bean, mixed  $tagList = NULL) : 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

mixed $tagList

tags to attach to the specified bean

Returns

string

addTags()

addTags(\RedBeanPHP\OODBBean  $bean, array  $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

array $tagList

list of tags to add to bean

tagged()

tagged(string  $beanType, array|string  $tagList, string  $sql = '', array  $bindings = array()) : array

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

array|string $tagList

list of tags to match

string $sql

additional SQL (use only for pagination)

array $bindings

bindings

Returns

array

taggedAll()

taggedAll(string  $beanType, array|string  $tagList, string  $sql = '', array  $bindings = array()) : array

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

array|string $tagList

list of tags to match

string $sql

additional sql snippet

array $bindings

bindings

Returns

array

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 Convience 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'.

Returns

boolean

commit()

commit() : boolean

Facade Convience 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'.

Returns

boolean

rollback()

rollback() : boolean

Facade Convience 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'.

Returns

boolean

getColumns()

getColumns(string  $table) : array

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

genSlots()

genSlots(array  $array, string  $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 $template

template to use

Returns

string

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.

storeAll()

storeAll(array  $beans) : array

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.

Parameters

array $beans

list of beans to be stored

Returns

array

trashAll()

trashAll(array  $beans) : void

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

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

Parameters

array $beans

list of beans to be trashed

trashBatch()

trashBatch(  $type,   $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 beeb 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

$type
$ids

hunt()

hunt(string  $type, string  $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 $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  $labels) : array

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 $labels

list of labels, names for each bean

Returns

array

enum()

enum(string  $enum) : array|\RedBeanPHP\OODBBean

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

Either returns a (newly created) bean respresenting 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

array|\RedBeanPHP\OODBBean

gatherLabels()

gatherLabels(array  $beans) : array

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 $beans

list of beans to loop

Returns

array

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(mixed  $time = NULL) : string

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

Parameters

mixed $time

UNIX timestamp

Returns

string

isoDateTime()

isoDateTime(mixed  $time = NULL) : string

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

Parameters

mixed $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\DBAdapter

Optional accessor for neat code.

Sets the database adapter you want to use.

Returns

\RedBeanPHP\Adapter\DBAdapter

getPDO()

getPDO() : NULL|\RedBeanPHP\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|\RedBeanPHP\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  $from, string  $to = NULL) : void

Facade method for AQueryWriter::renameAssociation()

Parameters

string|array $from
string $to

beansToArray()

beansToArray(array  $beans) : 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 $beans

beans

Returns

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  $data) : array

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 $data

either a bean or an array of beans

Returns

array

bindFunc()

bindFunc(string  $mode, string  $field, string  $function) : 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

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-existant) 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

findOrCreate()

findOrCreate(string  $type, array  $like = array(),   $sql = '') : \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

Returns

\RedBeanPHP\OODBBean

findLike()

findLike(string  $type, array  $like = array(), string  $sql = '', array  $bindings = array()) : array

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

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, convient 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

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

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

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

Returns

\RedBeanPHP\Logger

setAutoResolve()

setAutoResolve(boolean  $automatic = TRUE) : void

Alias for setAutoResolve() method on OODBBean.

Enables or disables auto-resolving fetch types. Auto-resolving aliased parent beans is convenient but can be slower and can create infinite recursion if you used aliases to break cyclic relations in your domain.

Parameters

boolean $automatic

TRUE to enable automatic resolving aliased parents

usePartialBeans()

usePartialBeans(boolean|array  $yesNoBeans) : mixed

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 $yesNoBeans

List of type names or 'all'

Returns

mixed

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) : mixed

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

mixed

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  $bean, \RedBeanPHP\OODBBean|array  $other, array  $filters = array('created', 'modified'),   $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 $bean

reference beans

\RedBeanPHP\OODBBean|array $other

beans to compare

array $filters

names of properties of all beans to skip

$pattern

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  $sql = NULL, array  $bindings = array()) 

Parameters

\RedBeanPHP\OODBBean $bean

bean to find children of

string $sql

optional SQL snippet

array $bindings

SQL snippet parameter bindings

parents()

parents(\RedBeanPHP\OODBBean  $bean, string  $sql = NULL, array  $bindings = array()) 

Parameters

\RedBeanPHP\OODBBean $bean

bean to find parents of

string $sql

optional SQL snippet

array $bindings

SQL snippet parameter bindings

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

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