Deleting foreign linked objects when using DatabaseObjects with the TurboDepot library

Introduction

In this tutorial, we will cover how to utilize the FOREIGN_DELETE_OBJECTS constant when working with database objects to delete related foreign objects automatically when an object is deleted.

In many database models, objects are interrelated through foreign keys, which means deleting an object might require deleting associated objects in other tables (foreign objects). The FOREIGN_DELETE_OBJECTS constant is designed to help manage this by enabling automatic deletion of foreign objects related to the primary object being deleted, without the need of creating database relations or constraints. All the underlying work is done by the library for us.

Understanding the FOREIGN_DELETE_OBJECTS Constant

The FOREIGN_DELETE_OBJECTS constant, when set on a DataBaseObject definition, instructs the system to delete any foreign objects that are related to the primary object being removed. This functionality is integrated into the DataBaseObject and DataBaseObjectsManager classes.

Prerequisites

  1. IMPORTANT: You should first read and understand the tutorial on how to create and save Database Objects
  2. Basic understanding of PHP and OOP (Object-Oriented Programming).
  3. Familiarity with database schemas and foreign key relationships.
  4. Access to an active database

Step-by-Step Guide

Step 1: Define Foreign Relationships in Your Object

Ensure that your database objects are configured to reference other objects that will be deleted in cascade once the primary one is deleted. The system will use these relationships to determine which objects to delete. You can do it easily as shown in the following example:

class User extends DataBaseObject {

    const FOREIGN_DELETE_OBJECTS = [
        'some\namespace\AnotherClassToDelete' => ['dbId' => 'userId']
    ];

    const TYPES = [

        'username' => [DataBaseObject::STRING, 50, DataBaseObject::NOT_NULL]
    ];

    public $username = '';
}

In this example, deleting a User object will trigger the deletion of all AnotherClassToDelete objects where the userId property matches the User's dbId. Notice that we may configure many more foreign classes to be deleted, as many as we want.

Step 2: Delete an existing object that has relationship with foreign objects

We should have some existing objects saved into our database (see previous tutorials for detailed info on how to save objects). The deletion process is triggered when any of the DataBaseObjectsManager delete methods is called (like deleteByDbIds() for example). Once we perform the removal of our main User object, all other existing database objects that match the FOREIGN_DELETE_OBJECTS rule will be also removed. The system encapsulates the deletion process within a database transaction. This ensures that either all objects (primary and foreign) are deleted, or none of them are deleted if an error occurs, providing consistency in the database.

The following code block illustrates how this works:

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();
$dbObjManager->deleteByDbIds(User::class, [1]);

Here we are removing a User object that has a dbId of 1 and all the related foreign objects that may exist.

Another way to do the same operation would be to use the deleteByInstances() method if we have a valid User instance loaded:

$user = $dbObjManager->findByDbId(User::class, 1);

// Deletes the user and all related AnotherClassToDelete instances
$dbObjManager->deleteByInstances([$user]);

The user is deleted, and because the FOREIGN_DELETE_OBJECTS constant is set, all AnotherClassToDelete objects with a userId of 1 are deleted as well.

Error Handling

If the deletion of foreign objects encounters issues the system will handle the error gracefully. If no related objects are found, the deletion of the main object will still happen.

Conclusion

The FOREIGN_DELETE_OBJECTS constant is a powerful feature for maintaining referential integrity in your database by ensuring that foreign objects are deleted alongside their related primary objects. This process is encapsulated within the DataBaseObjectsManager class and is executed via transactions for consistency. With proper implementation, it helps automate the cleanup of dependent objects and keeps your database free of orphaned records.