Create a Bean
Using RedBeanPHP is easy. First create a bean. A bean is an object with public properties. Every bean has an id and a type.
$book = R::dispense( 'book' );
Now we have an empty bean of type book. Let's add properties:
$book->title = 'Boost development with RedBeanPHP';
$book->author = 'Charles Xavier';
Now store it in the database:
$id = R::store($book);
That's all? Yes. Everything has been written to the database! RedBeanPHP automatically creates the required table, columns and indexes. Use the load() function to retrieve the bean from the database again.
How does it work?
Our bean has two properties, both strings. Thus RedBeanPHP will create a VARCHAR(255) column in the database (in this case MySQL). If we add a property:
$book->price = 100;
RedBeanPHP will add a TINYINT column. If we later add:
$book->price = 99.99;
RedBeanPHP will alter the column to make it possible to store a floating point number.
If you pass an SQL date like 2012-01-01 or a date-time value like 2012-01-01 12:00:00 RedBeanPHP will add a date/datetime column, if a column already exists a suitable type will be used that does not affect other data. You can also use MySQL spatial data types i.e. $bean->place="POINT(2 1)". A Spatial value string will be converted to its binary representation.
Note that the store() function returns the ID of the record. Also, there is storeAll($beans) in RedBeanPHP 3.1
Property names may only contain alphanumeric lowercase characters: a-z and 0-9 and underscores. Type names may contain lowercase alphanumeric characters a-z and 0-9. Underscores are reserved for linking tables.
Learn how to connect to a database with a single command.
Tweet
User contributed notes. Please use the comment section to provide tips, notes and examples. To ask for support or to provide feedback use the forum. For bug reports use Github Issue Tracker.
Site comments powered by Disqus