Home >Backend Development >PHP Tutorial >Introduction to Redbean
Core points
Introduction to RedBeanPHP
In Rapid Application Development (RAD) and prototyping, there are many tools to help you get started quickly. From quick starts to mini frameworks, from build tools like Composer to one-click installers, and of course ORM – there are a lot of ways to speed up development. We will focus on RedBeanPHP, a unique ORM that is perfect for prototyping.
Beginner of RedBeanPHP
RedBeanPHP is an ORM (Object Relational Mapper), but it is more than just an ORM - it can dynamically create and modify the underlying database schema. Traditionally, you would use ORM as a wrapper for pre-planned, pre-existing database schemas. This is OK for most projects, but when you are prototyping (or thinking while doing it), having it done for you in the background can speed up further.
When you create an object (or bean) with RedBeanPHP, the schema will automatically adjust to fit as long as you save it to the database. This applies even if you try to save an object that does not have a corresponding table!
Installation
The easiest way to install RedBeanPHP is to download the all-in-one package. Then you just need to introduce a single file rb.php
.
You can also install it through Composer; however, the library author does not recommend this method - see the installation page for details.
Distribute Bean
The first step in using RedBeanPHP is to "distribute" a bean - it is basically an object. Note that for the rest of this article, I use "bean" and objects interchangeably.
Distribution is done by the static method of the upper RedBean class "R", which takes the type as a parameter.
Example:
<code class="language-php">$user = R::dispense('user');</code>
This will create an empty user object that you can assign properties to. You can also distribute multiple beans simultaneously by adding the required number as the second parameter:
<code class="language-php">$users = R::dispense('user', 10);</code>
At this stage, it doesn't matter whether a table exists in the database to save it; as long as we try to store it, RedBeanPHP will handle it.
Let's try it out--Please note the use of the static method store
, which is used to write to the database:
<code class="language-php">$user = R::dispense('user');</code>
In most ORMs, this fails if you have not created a table to save the user. However, with RedBeanPHP, this will succeed because it will create the table for you. If you look at your database at this stage, you should see a table like this:
<code class="language-php">$users = R::dispense('user', 10);</code>
The naming convention is very strict due to the need; it is an singular, lowercase representation of the type you specify.
Now let's see how the pattern changes while iterating. User records may require a password field – but we forgot to create them.
If you do this:
<code class="language-php">$user->name = 'Joe Bloggs'; $user->email = 'joe.bloggs@example.com'; $id = R::store($user); print $id;</code>
This time, RedBeanPHP knows how to store users, but the database table cannot accommodate new fields. That's OK - it just adds one, your performance looks like this:
<code>user ---- id int(11) UN PK AI name varchar(255) email varchar(255)</code>
(The following content is similar to the original text, but the sentence structure and word adjustments have been made, and the image position and format are kept unchanged)
Field data type
RedBeanPHP will try to guess the data type of the field based on the information you provide. So if you do:
<code class="language-php">$user->password = 'secret'; R::store($user);</code>
You will find that the age field has been created as tinyint.
If the field type is insufficient later, RedBeanPHP will change it dynamically. If you now try to assign 3000 to age, the column will be changed to int. If you spell the name as "thirty", it will change to varchar. Set the varchar field to more than 255 characters, it will become a TEXT field, and so on.
Find Bean
You can use the load
method to load a specific object by primary key:
<code>user ---- id int(11) UN PK AI name varchar(255) email varchar(255) password varchar(255)</code>
You can use the batch
method to load multiple objects at once (press the primary key):
<code class="language-php">$user->age = 30; R::store($user);</code>
This will return an array of beans.
You can also use SQL to find beans. The second parameter of the find
method is essentially SQL starting with the WHERE clause, excluding the WHERE keyword itself. For example, to find users under 20 years old:
<code class="language-php">$user = R::load('user', 1);</code>
Note that we are binding the parameters, so the third parameter is an array. This will return an array of beans using its ID as key.
You can add more clauses to SQL, such as:
Count
You can use the count
method to find the number of records:
<code class="language-php">$users = R::batch('user', array(1, 2, 3));</code>
Delete
To delete a single bean, use trash
:
<code class="language-php">$users = R::find('user', 'age < 20');</code>
To delete multiple beans of a specific type, use trashAll
:
<code class="language-php">$number_of_users = R::count('user');</code>
To delete all beans of a specific type, use wipe
:
<code class="language-php">R::trash($user);</code>
Or, to delete everything – this can be useful when prototyping – you can use nuke
:
<code class="language-php">R::trashAll('user');</code>
Relationship
Like any ORM, the relationship between objects is supported.
One-to-many relationships use the concept of "owning" related objects to reference. For example, if the order has only one user, the user is called "own" the orders. By using specific variable names, we can create this relationship like this:
<code class="language-php">$user = R::dispense('user');</code>
The key element here is the attribute ownOrders
. If you check your database now, you should find that RedBeanPHP has added the field user_id
to the order table, along with the corresponding foreign keys.
Users who "own" the order can simply access as attributes, for example:
<code class="language-php">$users = R::dispense('user', 10);</code>
To demonstrate a many-to-many relationship, let's create some characters:
<code class="language-php">$user->name = 'Joe Bloggs'; $user->email = 'joe.bloggs@example.com'; $id = R::store($user); print $id;</code>
Roles are not just individual users; they are shared. So to assign the first two roles to the user and establish a relationship in the database when doing so, we can do this:
<code>user ---- id int(11) UN PK AI name varchar(255) email varchar(255)</code>
This time you should find a new table called role_user
which defines this relationship as a many-to-many relationship.
You can get the role that belongs to the user by reading the attribute:
<code class="language-php">$user->password = 'secret'; R::store($user);</code>
This delays loading of roles on the first time they are accessed.
Relationships have a lot more to it, including adding attributes to relationships using link
, filtering by link, urgent loading, etc. - please check the documentation for details.
Model
You can create models to correspond to bean types, just follow certain naming conventions. The model then connects to the bean using FUSE; that is, they are fused together by following the relevant naming conventions.
The convention is simple; use underscores to separate the "Model" from the type, such as Model_Type
. For example, to create a model for a user, you just need to do the following:
<code>user ---- id int(11) UN PK AI name varchar(255) email varchar(255) password varchar(255)</code>After defining the model, you can implement many methods that will be called at different points in the life cycle of the bean. The following table illustrates the mapping between the CRUD operation and the "hook" you can implement:
For example, you can add validation by implementing update()
:
<code class="language-php">$user = R::dispense('user');</code>
You can of course also create your own methods as well as customize GETters.
Query database
You can execute the original SQL query like this:
<code class="language-php">$users = R::dispense('user', 10);</code>
You can return a multidimensional array of rows like this:
<code class="language-php">$user->name = 'Joe Bloggs'; $user->email = 'joe.bloggs@example.com'; $id = R::store($user); print $id;</code>
In addition, you can use parameter binding:
<code>user ---- id int(11) UN PK AI name varchar(255) email varchar(255)</code>
You can get a single column like this:
<code class="language-php">$user->password = 'secret'; R::store($user);</code>
You can also get the associative array using two columns of the table:
<code>user ---- id int(11) UN PK AI name varchar(255) email varchar(255) password varchar(255)</code>
Deploy your application
While it is arguably the best for prototyping (or at least development)—you can follow certain steps, there is no reason why RedBeanPHP cannot continue to be used in production environments.
The mechanism of RedBeanPHP dynamic update mode is called "streaming mode"; however, this is not suitable for production environments and has considerable performance overhead. However, you can turn it off by "freezing" it:
<code class="language-php">$user->age = 30; R::store($user);</code>
When entering production, you need to follow the following steps:
Summary
In this article, I introduced RedBeanPHP, a convenient way to start your development process by allowing you to process domain models without having to build the underlying pattern first. Whether it is suitable for production environments remains to be seen – but it is a great gadget for prototyping and quick iteration. I'm not covering a lot, so be sure to check out the documentation.
RedBeanPHP FAQ
RedBeanPHP is a simple, lightweight object-relational mapping (ORM) tool that provides a range of features designed to simplify database interaction. It is known for its "zero configuration" approach, which means it requires only minimal setup and configuration. It automatically builds the database schema based on the objects you create, and can adjust the schema as needed when the object changes. RedBeanPHP also supports streaming mode and freezing mode, allowing you to easily switch between development and production environments. It includes a built-in tree structure and supports bean canning and distribution for easy storage and retrieval of objects.
Compared with other ORM tools, RedBeanPHP stands out for its simplicity and ease of use. It does not require configuration files, SQL or model classes. This makes it a great choice for beginners or projects where full-featured ORM appears redundant. However, it still offers powerful features such as automatic mode modification and tree structure, making it sufficient for more complex projects.
RedBeanPHP can be installed through Composer (a popular PHP dependency management tool). After installation, you can set up RedBeanPHP by including the RedBeanPHP file in the script and setting up a database connection. RedBeanPHP will automatically create and modify tables based on your objects.
Streaming mode is a feature of RedBeanPHP that allows it to automatically adjust the database schema when objects change. This can save a lot of time during development because you don't have to manually modify the database every time you change the object. However, it is recommended to switch to "freeze mode" in production environments for performance and safety reasons.
RedBeanPHP supports several relationship types between objects, including one-to-one, one-to-many, and many-to-many. These relationships are handled by using "bean" (a simple object representing rows in a database table). You can easily associate beans with each other to represent relationships between objects.
Yes, RedBeanPHP can be used with existing databases. However, please note that RedBeanPHP's automatic mode modification feature may change the database structure, so it is recommended to back up the database before using RedBeanPHP.
While RedBeanPHP is known for its simplicity and ease of use, it also offers powerful features that make it suitable for large and complex projects as well. Its automatic mode modification, support for various relationship types, and built-in tree structure are all very useful in large projects. However, for very large or complex projects, a more comprehensive ORM tool may be more suitable.
RedBeanPHP contains several features designed to enhance security. It uses preprocessing statements to help prevent SQL injection attacks and recommends using "freeze mode" in production to prevent unexpected schema changes. However, as with any tool, it is important to follow security best practices and keep RedBeanPHP up to date.
bean canning is a feature of RedBeanPHP that allows you to store and retrieve the entire bean (object) set at once. This can be a convenient way to handle large amounts of data, and can also help improve performance by reducing the number of database queries.
While Composer is the recommended method for installing RedBeanPHP, you can also download and include RedBeanPHP files directly into your script. However, using Composer makes it easier to manage and update RedBeanPHP and any other dependencies that a project may have.
The above is the detailed content of Introduction to Redbean. For more information, please follow other related articles on the PHP Chinese website!