📜  laravel 备份 - PHP (1)

📅  最后修改于: 2023-12-03 15:02:36.761000             🧑  作者: Mango

Laravel 备份 - PHP

Laravel 是一个流行的 PHP Web 应用程序开发框架,可以轻松创建和维护适用于各种项目的高质量 Web 应用程序。备份是一种重要的任务,可以确保应用程序和数据的完整性和安全。在 Laravel 应用程序中实现备份功能很重要,本文将介绍如何使用 Laravel 实现程序备份。

安装

首先,需要安装 Spatie Laravel Backup Package,这是一个 Laravel 很受欢迎的备份软件包,可帮助在 Laravel 应用程序中进行自动备份。

使用以下命令通过 composer 安装该软件包:

composer require spatie/laravel-backup

然后发布配置文件和语言文件:

php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider" --tag="config"
php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider" --tag="lang"

在 Laravel 5.5 或更高版本中, 该服务会自动注册.

配置

在应用程序中配置备份设置比较简单。 在 config/backups.php 文件中可以配置所有备份的设置。 包括要备份的文件和目录,备份保留时间,压缩文件设置以及备份存储位置等。

在配置文件中可以看到默认的设置。

return [

    'backup' => [

        /*
         * The name of this application. You can use this name to monitor
         * the backups.
         */
        'name' => env('APP_NAME'),

        'source' => [
            'files' => [
                /*
                 * The list of directories and files that will be included in the backup.
                 */
                'include' => [
                    base_path(),
                ],

                /*
                 * These directories and files will be excluded from the backup.
                 *
                 * Directories used by the backup process will automatically be excluded.
                 */
                'exclude' => [
                    base_path('vendor'),
                    base_path('node_modules'),
                ],

                /*
                 * Determines if symlinks should be followed.
                 */
                'follow_links' => false,
            ],

            /*
             * The names of the connections to the databases that should be backed up
             * MySQL, PostgreSQL, SQLite and Mongo databases are supported.
             */
            'databases' => [
                'mysql',
            ],
        ],

        /*
         * The database dump can be piped to a compression program like gzip or bzip2.
         *
         * This will save diskspace, but it will of course make the backup process
         * slower.
         */
        'database_dump_compressor' => null,

        'destination' => [

            /*
             * The filename prefix used for the backup zip file.
             */
            'filename_prefix' => '',

            /*
             * The disk names on which the backups will be stored.
             */
            'disks' => [
                'local',
            ],
        ],
    ],

    /*
     * You can get notified when specific events occur. Out of the box you can use 'mail' and 'slack'.
     * For Slack you need to install guzzlehttp/guzzle.
     *
     * You can also use your own notification classes, just make sure the class is named after one of
     * the `Spatie\Backup\Events` classes.
     */
    'notifications' => [

        'notifications' => [
            \Spatie\Backup\Notifications\Notifications\BackupHasFailed::class         => ['mail'],
            \Spatie\Backup\Notifications\Notifications\UnhealthyBackupWasFound::class => ['mail'],
            \Spatie\Backup\Notifications\Notifications\CleanupHasFailed::class        => ['mail'],
            \Spatie\Backup\Notifications\Notifications\BackupWasSuccessful::class     => ['mail'],
            \Spatie\Backup\Notifications\Notifications\HealthyBackupWasFound::class  => ['mail'],
            \Spatie\Backup\Notifications\Notifications\CleanupWasSuccessful::class    => ['mail'],
        ],

        /*
         * Here you can specify the notifiable to which the notifications should be sent. The default
         * notifiable will use the variables specified in this config file.
         */
        'notifiable' => \Spatie\Backup\Notifications\Notifiable::class,

        'mail' => [
            'to' => 'your@example.com',
        ],

        'slack' => [
            'webhook_url' => '',

            /*
             * If this is set to null the default channel of the webhook will be used.
             */
            'channel' => null,

            'username' => null,

            'icon' => null,

            /*
             * If true the context message specified in the config file will be included in the message
             * sent to Slack.
             */
            'include_context' => true,

            /*
             * Additional fields that should be included in the messages send to slack. You can add your own
             * fields here. These fields can be used in your own custom slack message formatter.
             *
             * These fields should be defined as key/value pairs.
             */
            'additional_fields' => [
                // 'environment' => app()->environment(),
            ],
        ],
    ],

    /*
     * Here you can specify the notification system that should be used when a backup
     * has failed. Possible values are "log", "array" and "null".
     */
    'notifier' => config('app.env') === 'production' ? null : 'log',

    /*
     * The `temporary_directory_path` specifies where the package should store temporary files.
     */
    'temporary_directory_path' => storage_path('app/backup-temp'),
];
备份任务的创建和运行

创建 Laravel 执行备份任务的命令。 必须在命令执行过程中初始化备份设置并运行备份命令。

namespace App\Console\Commands;

use Spatie\Backup\Tasks\Backup\BackupJobFactory;
use Illuminate\Console\Command;

class Backup extends Command
{
    protected $signature = 'backup';

    protected $description = 'Create a backup of the application';

    public function handle()
    {
        $backupJob = BackupJobFactory::createFromArray(config('backup'));

        $this->info('Starting backup...');

        $backupJob->run();

        $this->info('Backup completed successfully.');
    }
}

这里的 $signature 属性指定名称, $description 属性指定命令描述。

现在,可以在 Laravel 应用程序中使用以下命令运行备份任务:

php artisan backup
自动备份

可以使用 cron 作业自动化 Laravel 备份。 在 Linux 系统或 Mac 上,可以使用以下shell命令将备份任务添加到 crontab 中:

* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

然后,在 Laravel 应用程序中可以添加定期备份任务。 在 app/Console/Kernel.php 文件中添加以下任务:

$schedule->command('backup')->daily();

该示例中,备份将在每天自动运行,可以使用其他计划 cron 作业运行备份任务。该命令可以在 Laravel 应用程序中的任何地方使用。

结论

Laravel 提供了一个简单的备份流程,其实现需要提前安装 Spatie Laravel Backup Package 应用程序包。 上面的代码片段说明了如何使用 Laravel 进行备份以及如何设置和运行备份任务。现在,可以开始备份 Laravel 应用程序,以确保数据和应用程序的安全性和完整性,以便在必要时进行恢复。