PHP code example of i-kadar / cascading-deletion

1. Go to this page and download the library: Download i-kadar/cascading-deletion library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

i-kadar / cascading-deletion example snippets


class BasicEntityRepository extends EntityRepository {

    // Implementing the abstract method from EntityRepository
    public function getReferencedDeletionTargets(int $entityId): array {
        // Example logic: Retrieve IDs of entities referenced by the entity with the given ID
        // This is typically where you would query your database or data source
        // For simplicity, we're returning a static array of sample data
        return [
            new DeletionTarget(101, $this), // Assuming entity ID 101 is a dependent entity
            new DeletionTarget(102, $this)  // Assuming entity ID 102 is another dependent entity
        ];
    }

    // Implementing the abstract method from EntityRepository
    public function checkDeletability(DeletionTargetInterface $target, array $targets): bool {
        // Example logic: Check if the entity is deletable
        // This might involve checking certain conditions or rules
        // Returning true for simplicity
        return true;
    }

    // Implementing the abstract method from EntityRepository
    public function performDeletion(int $entityId): void {
        // Example logic: Perform the actual deletion of the entity
        // This is where you would typically delete the entity from your database or data source
        echo "Deleting entity with ID: " . $entityId . "\n";
    }
}

$cascadingDeletionService = new CascadingDeletionService();
$basicEntityRepository = new BasicEntityRepository();
$entity = new DeletionTarget(200, $basicEntityRepository);
list($deletionSuccessful, $undeletableEntities) = $cascadingDeletionService->deleteEntity($entity);

if ($deletionSuccessful) {
    echo "Entity was deleted successfully.\n";
} else {
    echo "Deletion was aborted due to undeletable dependents.\n";
    echo "Undeletable entities: \n";
    foreach ($undeletableEntities as $undeletableEntity) {
        echo "Entity ID: " . $undeletableEntity->getEntityId() . "\n";
        echo "Repository: " . get_class($undeletableEntity->getRepository()) . "\n";
        echo "Message: " . $undeletableEntity->getMessage() . "\n";
    }
}