varienos/mysql-backup
Composer 安装命令:
composer require varienos/mysql-backup
包简介
Modern MySQL database backup and restore utility with compression support
README 文档
README
Modern, efficient MySQL database backup and restore utility for PHP 7.4+
Features
- Modern PHP: Built with PHP 7.4+ features (type hints, PDO, PSR-4 autoloading)
- Memory Efficient: Batch processing to handle large databases without exhausting memory
- Compression Support: Optional gzip compression to save disk space
- Backup & Restore: Full backup and restore functionality
- Progress Tracking: Real-time logging and progress information
- Flexible Table Selection: Backup all tables or select specific ones
- CLI & Web Compatible: Works in both command-line and web environments
- Zero Dependencies: Core functionality requires only PHP and PDO extension
Requirements
- PHP >= 7.4
- PDO MySQL extension
- MySQL/MariaDB database
Installation
Using Composer (Recommended)
composer require varienos/mysql-backup
Manual Installation
-
Clone or download this repository:
git clone https://github.com/varienos/mysql-backup.git cd mysql-backup -
Install dependencies:
composer install
-
Verify installation:
php test-autoload.php
Quick Install with Make
If you have make installed:
make install # Install dependencies make check # Validate installation make test # Run tests
Quick Start
Creating a Backup
<?php require 'vendor/autoload.php'; use Varienos\MySQLBackup\MySQLBackup; $backup = new MySQLBackup( 'localhost', // host 'username', // username 'password', // password 'database_name' // database ); // Backup all tables $backup->backup('*'); // Get backup file path echo "Backup saved to: " . $backup->getLastBackupFile();
Restoring from Backup
<?php require 'vendor/autoload.php'; use Varienos\MySQLBackup\MySQLBackup; $backup = new MySQLBackup( 'localhost', 'username', 'password', 'database_name' ); // Restore from a backup file $backup->restore('sqlbackup/varienos-sql-backup-mydb-20241010_143000.sql.gz');
Configuration Options
$options = [ 'backup_dir' => 'sqlbackup', // Backup directory 'charset' => 'utf8mb4', // Database charset 'gzip' => true, // Enable gzip compression 'batch_size' => 2000, // Rows per batch 'disable_foreign_key_checks' => true, // Disable FK checks during restore ]; $backup = new MySQLBackup($host, $user, $pass, $db, $options);
Advanced Usage
Backup Specific Tables
// Backup specific tables (array) $backup->backup(['users', 'posts', 'comments']); // Backup specific tables (comma-separated string) $backup->backup('users, posts, comments');
List Available Backups
$backups = $backup->listBackups(); foreach ($backups as $file) { echo "{$file['file']} ({$file['size_formatted']}) - {$file['created_formatted']}\n"; }
Access Logs
$backup->backup('*'); // Get all log entries $logs = $backup->getLogs(); foreach ($logs as $log) { echo $log . "\n"; }
Examples
See the example-backup.php and example-restore.php files for complete working examples.
Running Examples
-
Ensure dependencies are installed:
composer install
-
Copy
.env.exampleto.envand configure your database credentials:cp .env.example .env # Edit .env with your database credentials -
Run the backup example:
php example-backup.php
-
Run the restore example:
php example-restore.php
Available Commands
Composer Commands
# Install dependencies composer install # Update dependencies composer update # Run tests composer test # Run tests with coverage composer test-coverage # Run specific test composer test-filter testBackupWithData # Validate composer.json composer validate # Optimize autoloader composer dump-autoload --optimize
Make Commands
make help # Show all available commands make install # Install composer dependencies make update # Update composer dependencies make autoload # Regenerate optimized autoloader make test # Run PHPUnit tests make test-coverage # Run tests with coverage report make check # Validate composer.json and test autoload make clean # Clean vendor and cache files
Performance Tips
- Batch Size: Adjust
batch_sizebased on your available memory. Larger batches are faster but use more memory. - Compression: Enable gzip compression to save disk space (typically 70-90% reduction).
- Foreign Key Checks: Disable during restore for faster imports.
Testing
This package includes a comprehensive test suite using PHPUnit.
Setup Test Environment
-
Install PHPUnit (if not already installed):
composer install --dev
-
Configure test database credentials in
phpunit.xml:<php> <env name="DB_HOST" value="localhost"/> <env name="DB_USER" value="root"/> <env name="DB_PASSWORD" value=""/> <env name="DB_NAME" value="test_backup_db"/> </php>
Or copy
.env.testing.exampleto.env.testingand configure your test credentials. -
Ensure test database user has permissions:
CREATE USER 'test_user'@'localhost' IDENTIFIED BY 'test_password'; GRANT ALL PRIVILEGES ON test_backup_db.* TO 'test_user'@'localhost'; FLUSH PRIVILEGES;
Running Tests
Run all tests:
./vendor/bin/phpunit
Run specific test class:
./vendor/bin/phpunit tests/MySQLBackupTest.php
Run with coverage report:
./vendor/bin/phpunit --coverage-html coverage-report
Run specific test method:
./vendor/bin/phpunit --filter testBackupWithData
Test Coverage
The test suite covers:
- ✅ Constructor and initialization with valid/invalid credentials
- ✅ Backup all tables (empty and with data)
- ✅ Backup specific tables (array and string format)
- ✅ Restore from compressed and uncompressed backups
- ✅ Gzip compression/decompression
- ✅ Batch processing with large datasets
- ✅ List backups with metadata
- ✅ Foreign key constraint handling
- ✅ Special character escaping in data
- ✅ Error handling and exceptions
- ✅ Logging system
Writing Custom Tests
Extend the base TestCase class for database test utilities:
<?php namespace Varienos\MySQLBackup\Tests; use Varienos\MySQLBackup\MySQLBackup; class MyCustomTest extends TestCase { public function testMyFeature(): void { // Create test database and tables $this->createTestDatabaseConnection(); $this->createSampleTables(); // Insert sample data $this->insertSampleData(10, 5); // Your test code here $backup = new MySQLBackup( $this->testDbHost, $this->testDbUser, $this->testDbPassword, $this->testDbName ); $this->assertTrue($backup->backup('*')); } }
Security Notes
- Never commit
.envfiles or hardcode credentials in version control - Store backup files in a secure location with appropriate permissions
- Regularly test your backup and restore procedures
- Consider encrypting sensitive backup files
License
MIT License
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
For security reports or general questions, reach out at hello@varien.dev.
varienos/mysql-backup 适用场景与选型建议
varienos/mysql-backup 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 48 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 10 月 12 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「database」 「compression」 「dump」 「mysql」 「backup」 「restore」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 varienos/mysql-backup 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 varienos/mysql-backup 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 varienos/mysql-backup 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
This package will add the `dd` and `dump` helpers to your Phalcon application.
Dibi is Database Abstraction Library for PHP
Asset Management for PHP
Image optimization / compression library. This library is able to optimize png, jpg and gif files in very easy and handy way. It uses optipng, pngquant, pngcrush, pngout, gifsicle, jpegoptim and jpegtran tools.
Simple Twig extension improving templates debugging
nice output for debug functions for PHP 5.3
统计信息
- 总下载量: 48
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 33
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-10-12