0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CakePHPで一定時間ごとにユーザのストレージ利用量を計算する。

Last updated at Posted at 2025-05-10

やりたいこと

ユーザのストレージ利用量を一定時間ごとに計算して、DBに登録する。

方針

CakePHPのコマンドオブジェクトを使い、cron実行する。

環境

・PHP8.1
・CakePHP5

コード

以下のコードを/src/Command/に設置すれば、コマンドから実行可能。

<?php
// /src/Command/StorageCommand.php
namespace App\Command;

use Cake\Command\Command;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\ORM\TableRegistry;

class StorageCommand extends Command
{
    public function execute(Arguments $args, ConsoleIo $io)
    {
        $usersTable = TableRegistry::getTableLocator()->get('Users');
        $users = $usersTable->find()->all();

        foreach ($users as $user) {
        //ユーザごとのファイル設置パス(任意)
            $userDir = WWW_ROOT . 'uploads/user_' . $user->id;

            $storageSizeMb = $this->getDirectorySize($userDir);

            $user->storage = $storageSizeMb;
            $usersTable->saveOrFail($user);
        }
    }

    protected function getDirectorySize($directory)
    {
        $totalSize = 0;

        if (!is_dir($directory)) {
            return 0;
        }

        $files = scandir($directory);

        foreach ($files as $file) {
            if ($file === '.' || $file === '..') {
                continue;
            }

            $filePath = $directory . '/' . $file;

            if (is_file($filePath)) {
                $totalSize += filesize($filePath);
            } elseif (is_dir($filePath)) {
                // 再帰的にサブディレクトリも含める
                $totalSize += $this->getDirectorySize($filePath);
            }
        }

        // バイト → MB(整数)
        return (int) floor($totalSize / 1024 / 1024); 
    }
}

コマンド実行

下記をCronで定期実行する。

/usr/bin/php8.1 path_to_cake/bin/cake.php storage

参考

・CakePHP5公式:コマンドオブジェクト

おまけ

無料でストレージ100Mまで利用可能です。
バグレポートツール「Altary」、ぜひ使ってみてください。
https://altary.io/

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?