PHP自动化部署与版本管理
PHP自动化部署与版本管理
自动化部署是现代开发的标准实践。从代码提交到上线,自动化流程可以减少人工操作。今天说说PHP项目的自动化部署。
版本号管理。
```php
class VersionManager
{
private string $versionFile;
private array $version;
public function __construct(string $versionFile = 'VERSION')
{
$this->versionFile = $versionFile;
$this->version = $this->load();
}
private function load(): array
{
if (file_exists($this->versionFile)) {
$parts = explode('.', trim(file_get_contents($this->versionFile)));
return ['major' => (int)($parts[0] ?? 1), 'minor' => (int)($parts[1] ?? 0), 'patch' => (int)($parts[2] ?? 0)];
}
return ['major' => 1, 'minor' => 0, 'patch' => 0];
}
public function get(): string
{
return "{$this->version['major']}.{$this->version['minor']}.{$this->version['patch']}";
}
public function bumpPatch(): string
{
$this->version['patch']++;
return $this->save();
}
public function bumpMinor(): string
{
$this->version['minor']++;
$this->version['patch'] = 0;
return $this->save();
}
private function save(): string
{
$version = $this->get();
file_put_contents($this->versionFile, $version);
return $version;
}
public function generateChangelog(array $changes): string
{
$version = $this->get();
$log = "## [{$version}] - " . date('Y-m-d') . "\n\n";
foreach ($changes as $type => $items) {
if (!empty($items)) {
$log .= "### {$type}\n";
foreach ($items as $item) $log .= "- {$item}\n";
$log .= "\n";
}
}
$changelog = file_exists('CHANGELOG.md') ? file_get_contents('CHANGELOG.md') : '';
file_put_contents('CHANGELOG.md', $log . $changelog);
return $version;
}
public function createGitTag(): void
{
$tag = "v" . $this->get();
exec("git tag -a {$tag} -m 'Release {$tag}'");
exec("git push origin {$tag}");
echo "Git Tag: {$tag}\n";
}
}
$v = new VersionManager();
echo "版本: {$v->get()}\n";
$v->bumpPatch();
echo "新版本: {$v->get()}\n";
?>
部署脚本。
```php
class Deployer
{
private string $repo;
private string $targetDir;
private string $branch;
public function __construct(string $repo, string $targetDir, string $branch = 'main')
{
$this->repo = $repo;
$this->targetDir = $targetDir;
$this->branch = $branch;
}
public function deploy(): void
{
echo "开始部署...\n";
if (!is_dir($this->targetDir)) {
exec("git clone -b {$this->branch} {$this->repo} {$this->targetDir}");
} else {
chdir($this->targetDir);
exec("git pull origin {$this->branch}");
}
chdir($this->targetDir);
exec("composer install --no-dev --optimize-autoloader 2>&1", $output, $code);
if ($code !== 0) throw new RuntimeException("Composer失败: " . implode("\n", $output));
exec("php artisan migrate --force");
exec("php artisan optimize");
echo "部署成功\n";
}
}
?>
自动化部署的核心是标准化。代码从Git拉取,依赖用Composer安装,数据库变更用迁移管理。每个步骤都自动化,不需要人工操作。部署失败能快速回滚到上一个版本。
