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

  1. Introduction
  2. Setting Up
  3. Connecting to the Database
  4. Creating and Saving Objects
  5. Retrieving Objects
  6. Updating Objects
  7. Deleting Objects
  8. Working with Array Properties
  9. Advanced Features
  10. 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:

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;

$dbManager = new DataBaseObjectsManager();

Connecting to the Database

Before performing any operations, you need to connect to your database. The class supports MySQL and MariaDB:

$dbManager->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 {
    public $username = '';
    public $email = '';
    public $age = 0;

    protected function setup(){

        $this->_types['username'] = [DataBaseObject::STRING, 50, DataBaseObject::NOT_NULL];
        $this->_types['email'] = [DataBaseObject::STRING, 100, DataBaseObject::NOT_NULL];
        $this->_types['age'] = [DataBaseObject::INT, 3];

        $this->_uniqueIndices[] = ['userName'];
    }
}

Let's break down the important elements:

Now, let's create and save a user:

$user = new User();
$user->username = 'johndoe';
$user->email = '[email protected]';
$user->age = 30;

$userId = $dbManager->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 = $dbManager->findByDbId(User::class, 1);

// Find by multiple IDs
$users = $dbManager->findByDbIds(User::class, [1, 2, 3]);

// Find by property values
$users = $dbManager->findByPropertyValues(User::class, ['username' => 'johndoe']);

Updating Objects

Updating objects is as simple as modifying their properties and saving them again:

$user->age = 31;
$dbManager->save($user);

Deleting Objects

You can delete objects using their instances or IDs:

// Delete by instance
$dbManager->deleteByInstances($user);

// Delete by ID
$dbManager->deleteByDbIds(User::class, [1, 2, 3]);

// Delete by property values
$dbManager->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 {
    public $title = '';
    public $tags = [];

    protected function setup(){

        $this->_types['title'] = [DataBaseObject::STRING, 200, DataBaseObject::NOT_NULL];

        // Here we are defining tags as an array of strings
        $this->_types['tags'] = [DataBaseObject::STRING, 50, DataBaseObject::ARRAY];
    }
}

Now you can work with array properties naturally:

$post = new Post();
$post->title = 'My First Blog Post';
$post->tags = ['php', 'tutorial', 'database'];
$dbManager->save($post);

Advanced Features

UUID Support

Enable UUID support for your objects:

$dbManager->isDbUUIDEnabled = true;

Trash Functionality

Enable the trash feature to soft-delete objects:

$dbManager->isTrashEnabled = true;

Custom Table Prefix

Set a custom prefix for your database tables:

$dbManager->tablesPrefix = 'myapp_';

Column Resizing

Allow columns to be automatically resized when values exceed their current size:

$dbManager->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!