- Getting started
- Basics
- Create a Bean
- Loading a Bean
- Deleting a Bean
- Freeze
- Finding
- Relation Mapping
- Models
- Database
- BeanCan
- Advanced
- Architecture
- Other
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 (and with id 0). 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 are strings so RedBeanPHP will create two VARCHAR(255) columns in the database (in this case MySQL). If we add a property:
$book->price = 100;
RedBeanPHP will add a TINYINT column. If we later change the value to:
$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 (and PostgreSQL since 3.2) spatial data types i.e. $bean->place="POINT(2 1)". A Spatial value string will be converted to its binary representation.
To generate SQL date and time values you can use: R::isoDate() and R::isoDateTime().
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. 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