How to save PHP objects directly into database without any SQL queries
In this tutorial, we'll explore the powerful DataBaseObjectsManager
class, a part of the TurboDepot library. This class provides a robust Object-Relational Mapping (ORM) solution for PHP applications, allowing you to seamlessly work with database objects in an object-oriented manner.
Table of Contents
- Introduction
- Setting Up
- Connecting to the Database
- Creating and Saving Objects
- Retrieving Objects
- Updating Objects
- Deleting Objects
- Working with Array Properties
- Advanced Features
- Conclusion
Introduction
The DataBaseObjectsManager
class is designed to simplify database operations by allowing you to work with PHP objects that directly correspond to database tables. It handles the complexities of database interactions, including table creation, modification, and querying, while you focus on working with familiar object-oriented code. But it is also SQL friendly as it stores all the data in a very organized and human readable way. This will allow you to perform any extra complex operation directly into the database with SQL if you want.
Setting Up
Before proceeding, ensure that the following requirements are met:
- PHP version 7 or higher.
- Ensure that you have the necessary PHP extensions for MySQL installed.
Download the latest TurboCommons and TurboDepot phar files and place them on your project as dependencies. Then you'll be able to directly use the DataBaseObjectsManager
class:
require 'path/to/your/dependencies/folder/turbocommons-php-X.X.X.phar';
require 'path/to/your/dependencies/folder/turbodepot-php-X.X.X.phar';
use org\turbodepot\src\main\php\managers\DataBaseObjectsManager;
$dbObjManager = new DataBaseObjectsManager();
Connecting to the Database
Before performing any operations, you need to connect to your database. The class supports MySQL and MariaDB:
$dbObjManager->connectMariaDb('localhost', 'username', 'password', 'database_name');
Creating and Saving Objects
To work with database objects, create a class that extends DataBaseObject
:
class User extends DataBaseObject {
const TYPES = [
'username' => [DataBaseObject::STRING, 50, DataBaseObject::NOT_NULL],
'email' => [DataBaseObject::STRING, 100, DataBaseObject::NOT_NULL],
'age' => [DataBaseObject::INT, 3]
];
const UNIQUEINDICES = [
['userName']
];
public $username = '';
public $email = '';
public $age = 0;
}
Let's break down the important elements:
- Each public property corresponds to a column in the database table.
- The TYPES array defines the data types and constraints for each property:
- The first element is the data type (STRING, INT, DOUBLE, BOOL, DATETIME).
- The second element is the size or precision.
- Additional elements can include constraints like NOT_NULL, NO_DUPLICATES, or ARRAY.
- The UNIQUEINDICES array allows you to define compound unique indices.
Now, let's create and save a user:
$user = new User();
$user->username = 'johndoe';
$user->email = '[email protected]';
$user->age = 30;
$userId = $dbObjManager->save($user);
echo "User saved with ID: $userId";
The save()
method automatically creates or updates the necessary database tables based on your object's structure and defined types.
Retrieving Objects
To retrieve objects from the database, you can use several methods:
// Find by ID
$user = $dbObjManager->findByDbId(User::class, 1);
// Find by multiple IDs
$users = $dbObjManager->findByDbIds(User::class, [1, 2, 3]);
// Find by property values
$users = $dbObjManager->findByPropertyValues(User::class, ['username' => 'johndoe']);
Updating Objects
Updating objects is as simple as modifying their properties and saving them again:
$user->age = 31;
$dbObjManager->save($user);
Deleting Objects
You can delete objects using their instances or IDs:
// Delete by instance
$dbObjManager->deleteByInstances($user);
// Delete by ID
$dbObjManager->deleteByDbIds(User::class, [1, 2, 3]);
// Delete by property values
$dbObjManager->deleteByPropertyValues(User::class, ['username' => 'johndoe']);
Working with Array Properties
The DataBaseObjectsManager class supports array properties. Define them in your class like this:
class Post extends DataBaseObject {
// Here we are defining tags as an array of strings
const TYPES = [
'title' => [DataBaseObject::STRING, 200, DataBaseObject::NOT_NULL],
'tags' => [DataBaseObject::STRING, 50, DataBaseObject::ARRAY]
];
public $title = '';
public $tags = [];
}
Now you can work with array properties naturally:
$post = new Post();
$post->title = 'My First Blog Post';
$post->tags = ['php', 'tutorial', 'database'];
$dbObjManager->save($post);
Advanced Features
UUID Support
Enable UUID support for your objects:
$dbObjManager->isDbUUIDEnabled = true;
Trash Functionality
Enable the trash feature to soft-delete objects:
$dbObjManager->isTrashEnabled = true;
Custom Table Prefix
The manager allows the use of a prefix for all tables it manages. By default, the prefix is set to td_
, but you can customize this:
$dbObjManager->tablesPrefix = 'myapp_'; // Change 'myapp_' to your desired prefix
This prefix ensures that all tables created by this class will avoid name collisions.
Column Resizing
Allow columns to be automatically resized when values exceed their current size:
$dbObjManager->isColumnResizedWhenValueisBigger = true;
Conclusion
The DataBaseObjectsManager
class provides a powerful and flexible way to work with database objects in PHP. By abstracting away the complexities of database operations, it allows you to focus on your application logic while ensuring efficient and type-safe data management.
Remember to always validate and sanitize user inputs, and consider implementing additional security measures like prepared statements for more complex queries. Happy coding!