CakePHP4 - Good location for functionality

My application needs to backup its database and image files on a regular basis. I’ve implemented this using a cakephp command that’s fired once a day using cron. This command uses mysqlsump and tar to create the backup files. Once these files are created, they’re copied across to an AWS S3 bucket and the local copies are deleted.

In the admin pages for the site, the list of backup files on S3 can be viewed, downloaded and deleted by an administrator. New backups can also be manually generated from the admin pages. The code for all this is in an ‘admin’ controller.

The command and controller currently duplicate code for creating the backup which isn’t great, plus both contain more code than I would like that actually does stuff rather than just orchestrating things.

I want to move this code that does stuff into somewhere it can be shared by both the command and the controller but I’m not sure where to put it.

Anybody got any advice on where it should go? I’m wondering if creating a plugin is the right thing or maybe a model (though there’s no database table so I’m not sure if that would work) or is there somewhere else for code like this?

I would personally implement such “heavy” logic in a queue task.
See GitHub - cakephp/queue: A queue-interop compatible Queueing library or GitHub - dereuromark/cakephp-queue: Queue plugin for CakePHP - simple, pure PHP and without dependencies.

With that you only add a task to the queue and a background worker (which always fetches the latest jobs) will do the job for you.

The logic inside that task of course can be quite vast and complex. Then I would go for something like a PHP generic service class, see my Cakefest talk explaining that.

Thanks @KevinPfeifer . I’ll have a look at this.

Thanks again @KevinPfeifer . I’ve just followed your example in the video and it worked perfectly (funny that your example was so similar to what I was trying to do with a controller action and a command).

1 Like