PHP code example of tobento / app-backup

1. Go to this page and download the library: Download tobento/app-backup 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/ */

    

tobento / app-backup example snippets


use Tobento\App\AppFactory;
use Tobento\App\Backup\Action;
use Tobento\App\Backup\Artifact;
use Tobento\App\Backup\Feature;
use Tobento\App\Backup\Hook;
use Tobento\App\Backup\Manifest;
use Tobento\App\Backup\Process;
use Tobento\App\Backup\Registry;
use Tobento\App\Backup\Repo;

// Create the app
$app = new AppFactory()->createApp();

// Add directories:
$app->dirs()
    ->dir(realpath(__DIR__.'/../'), 'root')
    ->dir(realpath(__DIR__.'/../app/'), 'app')
    ->dir($app->dir('app').'config', 'config', group: 'config')
    ->dir($app->dir('root').'public', 'public')
    ->dir($app->dir('root').'vendor', 'vendor');

// Adding boots
$app->boot(\Tobento\App\Backup\Boot\Backup::class);
$app->booting();

// Implemented interfaces:
$actionsFactory = $app->get(Action\ActionsFactoryInterface::class);
$backupProcessFactory = $app->get(Process\BackupProcessFactoryInterface::class);
$restoreProcessFactory = $app->get(Process\RestoreProcessFactoryInterface::class);
$readableArtifactFactory = $app->get(Artifact\ReadableArtifactFactoryInterface::class);
$writableArtifactFactory = $app->get(Artifact\WritableArtifactFactoryInterface::class);
$manifestFactory = $app->get(Manifest\ManifestFactoryInterface::class);
$backupRepository = $app->get(Repo\BackupRepositoryInterface::class);
$processRepository = $app->get(Repo\ProcessRepositoryInterface::class);
$restoreRepository = $app->get(Repo\RestoreRepositoryInterface::class);
$artifactRegistries = $app->get(Registry\Artifact\ArtifactRegistriesInterface::class);
$actionRegistries = $app->get(Registry\Action\ActionRegistriesInterface::class);
$hooks = $app->get(Hook\HooksInterface::class);

// Run the app
$app->run();

use Tobento\App\AppFactory;

// Create the app
$app = new AppFactory()->createApp();

// Add directories:
$app->dirs()
    ->dir(realpath(__DIR__.'/../'), 'root')
    ->dir(realpath(__DIR__.'/../app/'), 'app')
    ->dir($app->dir('app').'config', 'config', group: 'config')
    ->dir($app->dir('root').'public', 'public')
    ->dir($app->dir('root').'vendor', 'vendor');

// Adding boots
$app->boot(\Tobento\App\Backup\Boot\HttpErrorHandler::class);
$app->boot(\Tobento\App\Backup\Boot\Backup::class);
$app->booting();

// Run the app
$app->run();

'features' => [
    new Feature\Backups(
        // A menu name to show the translations link, or null for no menu entry.
        menu: 'main',
        menuLabel: 'Backups',
        // A menu parent name (e.g. 'system') or null if none.
        menuParent: null,
        
        // You may disable ACL while testing.
        // Otherwise, only users with the 

'features' => [
    new Feature\Restore(
        // A menu name to show the translations link, or null for no menu entry.
        menu: 'main',
        menuLabel: 'Restore Backups',
        // A menu parent name (e.g. 'system') or null if none.
        menuParent: null,

        // You may disable ACL while testing.
        // Otherwise, only users with the 

'features' => [
    new Feature\Processes(
        // A menu name to show the translations link, or null for no menu entry.
        menu: 'main',
        menuLabel: 'Backup/Restore Processes',
        // A menu parent name (e.g. 'system') or null if none.
        menuParent: null,

        // You may disable ACL while testing.
        // Otherwise, only users with the 

new Registry\Artifact\FileStorageArtifactRegistry(
    // A unique registry identifier used internally.
    id: 'ftp.storage',

    // Display name shown in the UI.
    name: 'FTP Storage',

    // The name of the configured storage service (e.g. ftp).
    storageName: 'ftp',

    // Optional folder inside the storage service where artifacts are stored.
    folder: 'backups/domain', // or null

    // Estimated throughput (bytes/sec), used for both write and read feasibility checks.
    throughputInBytes: 50_000_000,
),

new Registry\Artifact\ZipArtifactRegistry(
    // A unique registry identifier used internally.
    id: 'zip.local',

    // Display name shown in the UI.
    name: 'ZIP (Local Private Storage)',

    // Local storage path where ZIP artifacts are written and read.
    location: directory('app').'storage/uploads-private/backups/',

    // Estimated write throughput (bytes/sec), used for time‑window feasibility checks.
    throughputInBytes: 50_000_000,
),

use Tobento\App\Backup\Artifact\EncryptionWritableArtifact;

new EncryptionWritableArtifact(
    inner: $artifact, // any WritableArtifactInterface
    streamFactory: $streamFactory,
    encrypter: $encrypter, // Tobento\Service\Encryption\EncrypterInterface
    // Estimated encryption throughput (bytes/sec), used for time-window feasibility checks.
    throughputInBytes: 50_000_000,
),

yield new Field\Radios(name: 'meta.encrypt', label: trans('Encrypt Files'))
    ->group(trans('Backup'))
    ->options(['0' => trans('No'), '1' => trans('Yes')])
    ->selected(value: '0', action: 'create|edit')
    ->displayInline()
    ->infoText(new Html\Message(
        text: trans('Backup will fail when a file cannot be encrypted within the allowed processing window.'),
        warning: true,
        attributes: ['class' => 'mt-s mb-m'],
    ));

use Tobento\App\Backup\Artifact\EncryptionReadableArtifact;

new EncryptionReadableArtifact(
    inner: $artifact, // any ReadableArtifactInterface
    streamFactory: $streamFactory,
    encrypter: $encrypter, // Tobento\Service\Encryption\EncrypterInterface
),

new Registry\Action\AppDirectoryAction(
    // Display name shown in the UI.
    name: 'Vendor Directory',

    // The application identifier (e.g. 'root').
    appId: 'root',

    // The directory inside the application to back up.
    appDir: 'vendor',
),

new Registry\Action\AppDirectoryAction(
    name: 'Public Directory',
    appId: 'root',
    appDir: 'public',
),

new Registry\Action\AppDirectoryAction(
    name: 'Root Files',
    appId: 'root',
    appDir: 'root',

    // Only 

new Registry\Action\AppsDirectoryAction(
    // Display name shown in the UI.
    name: 'Apps Directory',

    // Additional subdirectories to  //except: ['api'],
),

new Registry\Action\DatabasesAction(
    name: 'Databases',
),

'hooks' => [
    new Hook\DeleteFailedBackupData(
        name: 'Auto‑Delete Failed Backup Data',
        group: 'Maintenance',
        defaultSelected: false,
    ),
]

'aliases' => [
    // Route deletion warnings to the "daily" logger:
    \Tobento\App\Backup\Hook\DeleteFailedBackupData::class => 'daily',

    // Or disable logging entirely:
    \Tobento\App\Backup\Hook\DeleteFailedBackupData::class => 'null',
];

'hooks' => [
    // Add this hook last:
    // It deletes the finished process entity,
    // so hooks that read the process entity from the repository must run earlier.
    new Hook\DeleteFinishedProcess(
        name: 'Auto‑Delete Finished Process (removes it from the process list)',
        group: 'Maintenance',
        defaultSelected: false,
    ),
]

'aliases' => [
    // Route deletion warnings to the "daily" logger:
    \Tobento\App\Backup\Hook\DeleteFinishedProcess::class => 'daily',

    // Or disable logging entirely:
    \Tobento\App\Backup\Hook\DeleteFinishedProcess::class => 'null',
];

'hooks' => [

    new Hook\Notify(
        // Unique identifier:
        id: 'notify.user',

        // Display name shown in the UI:
        name: 'Notify Developer via Mail and SMS',
        
        // Define the recipient:
        recipient: new Recipient(
            email: '[email protected]',
            phone: '15556666666',
            channels: ['mail', 'sms'],
        ),

        // Subject template (optional):
        notificationSubject: 'Job :name :event',

        // Queue name (optional):
        queueName: null, // e.g. 'file'

        // Events to notify on:
        notifyOn: [
            'started',
            'stepExecuting',
            'stepExecuted',
            'actionFinished',
            'finished',
            'failed',
        ],

        // Optional grouping label used in the UI (default: 'Notify'):
        group: 'Notify',

        // Should this hook be pre-selected in the UI?
        defaultSelected: true,
    ),
]

'hooks' => [

    new Hook\NotifyCurrentUser(
        // Unique identifier:
        id: 'notify.current-user',
        
        // Display name shown in the UI:
        name: 'Keep me updated about this job',
        
        // Channels used to notify the current user:
        channels: ['browser'],
        
        // Customize the notification subject (optional):
        notificationSubject: 'Job :name :event',
        
        // Events to notify on (optional):
        notifyOn: [
            'started',
            'stepExecuting',
            'stepExecuted',
            'actionFinished',
            'finished',
            'failed',
        ],
        
        // Send the notification via queue (optional):
        queueName: 'file', // null by default
        
        // Should this hook be pre-selected in the UI?
        defaultSelected: true,
        
        // Optional grouping label used in the UI (default: 'Notify'):
        group: 'Notify',
    ),
]

'hooks' => [

    new Hook\NotifyUsers(
        // Unique identifier:
        id: 'notify.administrators',

        // Display name shown in the UI:
        name: 'Notify Administrators via Account and Browser',
        
        // Roles whose users should be notified:
        roles: ['administrator'],
        
        // Channels used to notify these users:
        channels: ['storage', 'browser'],
        
        // Customize the notification subject (optional):
        notificationSubject: 'Job :name :event',
        
        // Maximum number of users to notify:
        limit: 100,
        
        // Send the notification via queue (optional):
        queueName: 'file', // null by default
        
        // Events to notify on:
        notifyOn: [
            'started',
            'stepExecuting',
            'stepExecuted',
            'actionFinished',
            'finished',
            'failed',
        ],
        
        // Should this hook be pre-selected in the UI?
        defaultSelected: false,
        
        // Optional grouping label used in the UI (default: 'Notify'):
        group: 'Notify',
    ),
]

use Tobento\App\Backup\Hook;

protected function mandatoryHooks(): array
{
    return [
        new Hook\ProcessLifecycle(name: 'Process Lifecycle'),
    ];
}

use Tobento\App\Backup\Queue\BackupJobHandler;

class CustomBackupJobHandler extends BackupJobHandler
{
    protected function mandatoryHooks(): array
    {
        return [
            new MyCustomProcessLifecycleHook(name: 'Custom Process Lifecycle'),
        ];
    }
}

use Tobento\App\Backup\Queue\BackupJobHandler;

'interfaces' => [
    BackupJobHandler::class => CustomBackupJobHandler::class,
],

'hooks' => [

    new Hook\SendGeneratedBackupZipToEmail(
        // Unique identifier:
        id: 'send.backup.zip',

        // Display name shown in the UI:
        name: 'Send Backup ZIP to Email',

        // Recipient email address:
        email: '[email protected]',

        // Email subject (supports {name} placeholder):
        subject: 'Backup Completed: {name}',

        // Email message body:
        message: 'Your backup has completed successfully. The ZIP file is attached.',

        // Optional grouping label used in the UI (default: 'Delivery'):
        group: 'Delivery',

        // Should this hook be pre-selected in the UI?
        defaultSelected: false,
    ),
]

'aliases' => [

    // Route backup ZIP delivery logs to the "daily" logger:
    \Tobento\App\Backup\Hook\SendGeneratedBackupZipToEmail::class => 'daily',

    // Or disable logging entirely:
    \Tobento\App\Backup\Hook\SendGeneratedBackupZipToEmail::class => 'null',
];

use Tobento\App\Backup\Task\BackupRegistry;

'registries' => [
    'backup.run' => new BackupRegistry(
        name: 'Run backups',
        
        // You may add task parameters to be always processed:
        parameters: [
            new \Tobento\Service\Schedule\Parameter\WithoutOverlapping(),
        ],
        
        // Define the supported apps where the task can be run:
        supportedAppIds: ['root', 'backend'],
    ),
]

use Tobento\App\Backup\Task\PruneBackupsRegistry;

'registries' => [
    'backup.prune' => new PruneBackupsRegistry(
        name: 'Prune backups',

        // You may add task parameters to be always processed:
        parameters: [
            new \Tobento\Service\Schedule\Parameter\WithoutOverlapping(),
        ],

        // Define the supported apps where the task can be run:
        supportedAppIds: ['root', 'backend'],
    ),
]

'interfaces' => [
    BackupRuntimeConfigInterface::class => function () {
        return new BackupRuntimeConfig(
            // Run backups and restores on a specific queue.
            // If null, the default queue is used.
            // **Synchronous execution (without a queue) is not supported.**
            // Backup and restore processes           jobTimeBudgetInSeconds: 20,
            
            // Name of the encrypter to use for encryption.
            encrypter: 'default',

            // Estimated encryption throughput in bytes per second.
            encryptThroughputInBytes: 50_000_000,
        );
    },
]

use Tobento\App\Backup\Registry\Action\ActionRegistriesInterface;
use Tobento\App\Backup\Registry\Action\ActionRegistryInterface;
use Tobento\App\Backup\Registry\Artifact\ArtifactRegistriesInterface;
use Tobento\App\Backup\Registry\Artifact\ArtifactRegistryInterface;

$app->on(
    ActionRegistriesInterface::class,
    static function(ActionRegistriesInterface $registries): void {
        $registries->add(
            registry: $registry, // ActionRegistryInterface
        );
    }
);

$app->on(
    ArtifactRegistriesInterface::class,
    static function(ArtifactRegistriesInterface $registries): void {
        $registries->add(
            registry: $registry, // ArtifactRegistryInterface
        );
    }
);

use Tobento\App\Backup\Hook\HooksInterface;
use Tobento\App\Backup\Hook\SendGeneratedBackupZipToEmail;

$app->on(
    HooksInterface::class,
    static function(HooksInterface $hooks): void {
        $hooks->add(
            id: 'mail.dev',
            hook: new SendGeneratedBackupZipToEmail(
                id: 'mail.dev',
                name: 'Mail Developer',
                email: '[email protected]',
                subject: 'Backup Completed: {name}',
                message: 'The backup ZIP is attached.',
            ),
        );
    }
);