C_REDBEANPHP_VERSION
C_REDBEANPHP_VERSION
RedBeanPHP version constant.
RedBean Facade
Version Information RedBean Version @version 5.7
This class hides the object landscape of RedBeanPHP behind a single letter class providing almost all functionality with simple static calls.
$toolbox : \RedBeanPHP\ToolBox
$toolboxes : array<mixed,\RedBeanPHP\ToolBox>
$redbean : \RedBeanPHP\OODB
$writer : \RedBeanPHP\QueryWriter
$adapter : \RedBeanPHP\Adapter
$associationManager : \RedBeanPHP\AssociationManager
$tagManager : \RedBeanPHP\TagManager
$duplicationManager : \RedBeanPHP\DuplicationManager
$labelMaker : \RedBeanPHP\LabelMaker
$finder : \RedBeanPHP\Finder
$tree : \RedBeanPHP\Util\Tree
$logger : \RedBeanPHP\Logger
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.
boolean | $hybrid |
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:
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.
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 |
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.
$mode |
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.
boolean | $mode | allow fluid transaction mode |
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.
$mode |
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); });
callable | $callback | Closure (or other callable) with the transaction logic |
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.
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(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:
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.
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 |
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.
string | $key | the key/name of the database to check for |
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).
string | $key | Key of the database to select |
boolean | $force |
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.
boolean | $tf | debug mode (TRUE or FALSE) |
integer | $mode | mode of operation |
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.
boolean | $toggle | TRUE to activate debugger and select 'fancy' mode |
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.
string|NULL | $type | Type of bean (i.e. table) you want to inspect, or NULL for a list of all tables |
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.
\RedBeanPHP\OODBBean|\RedBeanPHP\SimpleModel | $bean | bean to store |
boolean | $unfreezeIfNeeded | retries in fluid mode in hybrid mode |
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.
boolean|array<mixed,string> | $tf | mode of operation (TRUE means frozen) |
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 );
string|array<mixed,string> | $types | the set of types to load at once |
integer | $id | the common ID |
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.
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) |
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 );
string | $type | type of bean you want to load |
integer | $id | ID of the bean you want to load |
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 );
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 |
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.
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 |
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.
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(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' => '...'] ]
] );
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 |
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.
string | $order | a description of the desired dispense order using the syntax above |
boolean | $onlyArrays | return only arrays even if amount < 2 |
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.
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 |
findOneOrDispense(string $type, string|NULL $sql = NULL, array $bindings = array()) : \RedBeanPHP\OODBBean
Same as findOrDispense but returns just one element.
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 |
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.
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) |
findAll(string $type, string|NULL $sql = NULL, array $bindings = array()) : array<mixed,\RedBeanPHP\OODBBean>
Alias for find().
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 |
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.
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 |
findOne(string $type, string|NULL $sql = NULL, array $bindings = array()) : \RedBeanPHP\OODBBean|NULL
Like R::find() but returns the first bean only.
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 |
findLast(string $type, string|NULL $sql = NULL, array $bindings = array()) : \RedBeanPHP\OODBBean|NULL
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 |
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.
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 |
None found |
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'.
}
)
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 |
note |
the SQL query provided IS NOT THE ONE used internally by this function, this function will pre-process the query to get all the data required to find the beans. if you use the 'book.' notation make SURE you're selector starts with a SPACE. ' book.' NOT ',book.*'. This is because it's actually an SQL-like template SLOT, not real SQL. instead of an SQL query you can pass a result array as well. |
---|
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.
string | $type | type of beans |
array<mixed,integer> | $ids | ids to load |
None found |
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.
string | $type | type of beans |
array<mixed,integer> | $ids | ids to load |
None found |
exec(string $sql, array $bindings = array()) : integer
Convenience function to execute Queries directly.
Executes SQL.
string | $sql | SQL query to execute |
array | $bindings | a list of values to be bound to query parameters |
None found |
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.
string | $sql | SQL query to execute |
array | $bindings | a list of values to be bound to query parameters |
None found |
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.
string | $sql | SQL query to execute |
array | $bindings | a list of values to be bound to query parameters |
None found |
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.
string | $sql | SQL query to execute |
array | $bindings | a list of values to be bound to query parameters |
None found |
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.
string | $sql | SQL query to execute |
array | $bindings | a list of values to be bound to query parameters |
None found |
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.
string | $sql | SQL query to execute |
array | $bindings | a list of values to be bound to query parameters |
None found |
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.
string | $sql | SQL query to execute |
array | $bindings | a list of values to be bound to query parameters |
None found |
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.
string | $sql | SQL query to execute |
array | $bindings | a list of values to be bound to query parameters |
None found |
getInsertID() : integer
Returns the insert ID for databases that support/require this functionality. Alias for R::getAdapter()->getInsertID().
None found |
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.
Note: This function does a reflectional database query so it may be slow.
\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 |
None found |
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:
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.
\RedBeanPHP\OODBBean | $bean | bean to be copied |
array | $filters | white list filter with bean types to duplicate |
None found |
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:
\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 |
None found |
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:
string | $caseStyle | case style identifier |
warning |
RedBeanPHP transforms camelCase to snake_case using a slightly different algorithm, it also converts isACL to is_acl (not is_a_c_l) and bookID to book_id. Due to information loss this cannot be corrected. However if you might try DolphinCase for IDs it takes into account the exception concerning IDs. |
---|
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'.
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) |
None found |
convertToBean(string $type, array<mixed,string> $row, string|array|NULL $metamask = NULL) : \RedBeanPHP\OODBBean|NULL
Just like convertToBeans, but for one bean.
string | $type | type of bean to produce |
array<mixed,string> | $row | one row from the database |
string|array|NULL | $metamask | metamask (see convertToBeans) |
None found |
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.
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 |
None found |
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.
\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 |
None found |
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'.
\RedBeanPHP\OODBBean | $bean | tagged bean |
string|array<mixed,string> | $tagList | list of tags (names) |
None found |
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.
\RedBeanPHP\OODBBean | $bean | bean to tag |
array<mixed,string>|NULL | $tagList | tags to attach to the specified bean |
None found |
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.
\RedBeanPHP\OODBBean | $bean | bean to tag |
string|array<mixed,string> | $tagList | list of tags to add to bean |
None found |
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.
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 |
None found |
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'.
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 |
None found |
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).
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 |
None found |
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).
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 |
None found |
wipe(string $beanType) : boolean
Wipes all beans of type $beanType.
string | $beanType | type of bean you want to destroy entirely |
None found |
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.
string | $type | type of bean we are looking for |
string | $addSQL | additional SQL snippet |
array | $bindings | parameters to bind to SQL |
None found |
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.
\RedBeanPHP\ToolBox | $tb | toolbox to configure facade with |
None found |
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.
None found |
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.
None found |
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.
None found |
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!
string | $table | name of the table (not type) you want to get columns of |
None found |
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( ?,? ) '.
array | $array | array to generate question mark slots for |
string|NULL | $template | template to use |
None found |
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)]
);
array<mixed,\RedBeanPHP\OODBBean> | $beans | a list of OODBBeans |
string | $type | a type string |
string | $sqlTemplate | an SQL template string for the SELECT-query |
None found |
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' ]
array | $array | array to flatten |
array | $result | result array parameter (for recursion) |
None found |
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.
warning |
dangerous method, will remove all tables, columns etc. |
---|
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.
boolean | $alsoDeleteTables | TRUE to clear entire database. |
None found |
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.
array<mixed,\RedBeanPHP\OODBBean> | $beans | list of beans to be stored |
boolean | $unfreezeIfNeeded | retries in fluid mode in hybrid mode |
ids
None found |
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.
array<mixed,\RedBeanPHP\OODBBean> | $beans | list of beans to be trashed |
None found |
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.
string | $type | the bean type you wish to trash |
array<mixed,integer> | $ids | list of bean IDs |
None found |
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.
string | $type | bean type to look for in database |
string|NULL | $sqlSnippet | an SQL query snippet |
array | $bindings | SQL parameter bindings |
None found |
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.
boolean | $yesNo | TRUE to enable cache, FALSE to disable cache |
None found |
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.
string | $type | type of beans you would like to have |
array<mixed,string> | $labels | list of labels, names for each bean |
None found |
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' ) );
string | $enum | either type or type-value |
None found |
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).
array<mixed,\RedBeanPHP\OODBBean> | $beans | list of beans to loop |
None found |
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();
None found |
isoDate(integer|NULL $time = NULL) : string
Simple convenience function, returns ISO date formatted representation of $time.
integer|NULL | $time | UNIX timestamp |
None found |
isoDateTime(integer|NULL $time = NULL) : string
Simple convenience function, returns ISO date time formatted representation of $time.
integer|NULL | $time | UNIX timestamp |
None found |
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.
\RedBeanPHP\Adapter | $adapter | Database Adapter for facade to use |
None found |
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'.
\RedBeanPHP\QueryWriter | $writer | Query Writer instance for facade to use |
None found |
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).
\RedBeanPHP\OODB | $redbean | Object Database for facade to use |
None found |
getDatabaseAdapter() : \RedBeanPHP\Adapter
Optional accessor for neat code.
Sets the database adapter you want to use.
None found |
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.
None found |
getDuplicationManager() : \RedBeanPHP\DuplicationManager
Returns the current duplication manager instance.
None found |
getWriter() : \RedBeanPHP\QueryWriter
Optional accessor for neat code.
Sets the database adapter you want to use.
None found |
getRedBean() : \RedBeanPHP\OODB
Optional accessor for neat code.
Sets the database adapter you want to use.
None found |
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.
None found |
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:
None found |
renameAssociation(string|array<mixed,string> $from, string $to = NULL) : void
Facade method for AQueryWriter::renameAssociation()
string|array<mixed,string> | $from | |
string | $to |
None found |
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.
array<mixed,\RedBeanPHP\OODBBean> | $beans | beans |
None found |
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:
Custom handler method signature: handler( array (
'message' => string
'bean' => OODBBean
'method' => string
) )
This method returns the old mode and handler as an array.
integer | $mode | mode, determines how to handle errors |
callable|NULL | $func | custom handler (if applicable) |
None found |
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.
\RedBeanPHP\OODBBean|array<mixed,\RedBeanPHP\OODBBean> | $data | either a bean or an array of beans |
None found |
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.
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 |
None found |
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.
array<mixed,string> | $list | list of global aliases to use |
None found |
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.
string | $type | type of bean to search for |
array | $like | criteria set describing the bean to search for |
$sql | ||
$hasBeenCreated |
None found |
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.
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 |
None found |
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.
note |
you cannot use R::debug and R::startLogging at the same time because R::debug is essentially a special kind of logging. |
---|
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.
note |
you cannot use R::debug and R::startLogging at the same time because R::debug is essentially a special kind of logging. by stopping the logging you also flush the logs. Therefore, only stop logging AFTER you have obtained the query logs using R::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).
note |
you cannot use R::debug and R::startLogging at the same time because R::debug is essentially a special kind of logging. by stopping the logging you also flush the logs. Therefore, only stop logging AFTER you have obtained the query logs using R::getLogs() |
---|
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.';
None found |
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.';
None found |
getLogger() : \RedBeanPHP\Logger|NULL
Returns the current logger instance being used by the database object.
None found |
None found |
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.
boolean|array<mixed,string> | $yesNoBeans | List of type names or 'all' |
None found |
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.
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 |
None found |
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.
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 |
None found |
getLook() : \RedBeanPHP\Util\Look
None found |
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.
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 |
None found |
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'.
\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' |
None found |
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.
string | $key | key to store toolbox instance under |
\RedBeanPHP\ToolBox | $toolbox | toolbox to register |
None found |
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.
string | $key | identifier of the toolbox to remove |
None found |
getToolBoxByKey(string $key) : \RedBeanPHP\ToolBox|NULL
Returns the toolbox associated with the specified key.
string | $key | key to store toolbox instance under |
None found |
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).
boolean | $flag | feature flag (either TRUE or FALSE) |
None found |
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.
\RedBeanPHP\OODBBean | $bean | bean to find children of |
string|NULL | $sql | optional SQL snippet |
array | $bindings | SQL snippet parameter bindings |
note |
that not all database support this functionality. You'll need at least MariaDB 10.2.2 or Postgres. This method does not include a warning mechanism in case your database does not support this functionality. |
---|
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.
\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) |
note |
that not all database support this functionality. You'll need at least MariaDB 10.2.2 or Postgres. This method does not include a warning mechanism in case your database does not support this functionality. : You are allowed to use named parameter bindings as well as numeric parameter bindings (using the question mark notation). However, you can not mix. Also, if using named parameter bindings, parameter binding key ':slot0' is reserved for the ID of the bean and used in the query. : By default, if no select is given or select=TRUE this method will subtract 1 of the total count to omit the starting bean. If you provide your own select, this method assumes you take control of the resulting total yourself since it cannot 'predict' what or how you are trying to 'count'. |
---|
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.
\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) |
note |
that not all database support this functionality. You'll need at least MariaDB 10.2.2 or Postgres. This method does not include a warning mechanism in case your database does not support this functionality. : You are allowed to use named parameter bindings as well as numeric parameter bindings (using the question mark notation). However, you can not mix. Also, if using named parameter bindings, parameter binding key ':slot0' is reserved for the ID of the bean and used in the query. : By default, if no select is given or select=TRUE this method will subtract 1 of the total count to omit the starting bean. If you provide your own select, this method assumes you take control of the resulting total yourself since it cannot 'predict' what or how you are trying to 'count'. |
---|
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.
\RedBeanPHP\OODBBean | $bean | bean to find parents of |
string|NULL | $sql | optional SQL snippet |
array | $bindings | SQL snippet parameter bindings |
note |
that not all database support this functionality. You'll need at least MariaDB 10.2.2 or Postgres. This method does not include a warning mechanism in case your database does not support this functionality. |
---|
noNuke( $yesNo) : boolean
Toggles support for nuke().
Can be used to turn off the nuke() feature for security reasons. Returns the old flag value.
$yesNo |
None found |
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.
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 |
None found |
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.
string|array | $camel | camelCased string to convert to snake case |
None found |
useFeatureSet(string $label) : void
Selects the feature set you want as specified by the label.
Usage:
R::useFeatureSet( 'novice/latest' );
string | $label | label |
None found |
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();
string | $pluginName | name of the method to call the plugin |
callable | $callable | a PHP callable |
None found |
__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.
string | $pluginName | name of the plugin |
array | $params | list of arguments to pass to plugin method |
None found |
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.
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 |
None found |