LoginSignup
0
1

More than 1 year has passed since last update.

CakePHPでデータベースをdumpする

Last updated at Posted at 2022-12-07

データベースのバックアップを取りたいけど、いちいちDBにアクセスしてdumpするの面倒だし、どうせなら自動で実行できるようにしたい。
直接書いてもいいんだけど、CakePHP入れてるんだからそれっぽくしたいという、需要があるのかないのかよくわからない記事です。

環境

CakePHP 4.3
MySQL 5.7

コマンドを作成する

CakePHPをcrontabから実行するためにはコマンドを使います。
以前はシェルでしたが、CakePHP3.6から非推奨になり、代わりにコマンドを使うことが推奨されています。
https://book.cakephp.org/4/ja/console-commands/commands.html

cd [cakephpのディレクトリ]
# 「backup」という名前のコマンドを作成
bin/cake bake command backup

src/Command内にBackupCommand.phpが作成されます。
中身はこんな感じです。

src/Command/backupCommand.php
declare(strict_types=1);

namespace App\Command;

use Cake\Command\Command;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Console\ConsoleOptionParser;

/**
 * Backup command.
 */
class BackupCommand extends Command
{
    /**
     * Hook method for defining this command's option parser.
     *
     * @see https://book.cakephp.org/4/en/console-commands/commands.html#defining-arguments-and-options
     * @param \Cake\Console\ConsoleOptionParser $parser The parser to be defined
     * @return \Cake\Console\ConsoleOptionParser The built parser.
     */
    public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
    {
        $parser = parent::buildOptionParser($parser);

        return $parser;
    }

    /**
     * Implement this method with your command's logic.
     *
     * @param \Cake\Console\Arguments $args The command arguments.
     * @param \Cake\Console\ConsoleIo $io The console io
     * @return null|void|int The exit code or null for success
     */
    public function execute(Arguments $args, ConsoleIo $io)
    {
    }
}

バックアップ実行用プログラム

executeが実行されるメソッドなので、この中にプログラムを書いていきます。
DB情報はConnectionManagerから取得します。

src/Command/backupCommand.php
use Cake\Datasource\ConnectionManager;
use Cake\I18n\FrozenTime;

class BackupCommand extends Command
{
    ...
    public function execute(Arguments $args, ConsoleIo $io)
    {
        $current = new FrozenTime();
        $connection = ConnectionManager::get('default');
        $conf = $connection->config();
		$host = $conf['host'];
		$user = $conf['username'];
		$pass = $conf['password'];
		$name = $conf['database'];

        $file = ROOT . DS . 'bkup' . DS . $current->format('Ymd') .'.sql';
        $command = 'mysqldump ' . $name . ' --host=' . $host . ' --user=' . $user . ' --password=' . $pass . ' > ' . $file;
        system($command);
        $io->out(json_encode($file));
    }
}

実行

SSHで以下コマンドを実行します。
※bkupディレクトリは先に作っておきましょう。

bin/cake backup

しばらく待ちます。
ファイル名が表示されれば成功です。

crontabを設定

パスはご自身の環境に合わせてください。

# 毎日0時に実行
0 0 * * * /usr/bin/php7.3 /var/www/html/bin/cake.php backup

余談

コマンド内でTimeクラスを使おうとしたらFrozenTimeを使えと怒られたので、何で???と思ったらちゃんと書いてありました。
Viewで使うならTime、Viewの外で使う場合はFrozenTimeだそうです。
https://book.cakephp.org/4/ja/core-libraries/time.html

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1