Skip to content

Instantly share code, notes, and snippets.

@chopstik
Last active April 19, 2022 00:07
Show Gist options
  • Save chopstik/d695d089976012137501c4136513450d to your computer and use it in GitHub Desktop.
Save chopstik/d695d089976012137501c4136513450d to your computer and use it in GitHub Desktop.
CakePHP Shell to make use of UpdateCounterCache.php
<?php
namespace App\Shell;
use Cake\Console\Shell;
/**
* UpdateCounterCaches shell command.
*/
class UpdateCounterCachesShell extends Shell
{
/**
* Current models with counterCache behaviours attached. Edit prior to use.
* @var array $_models
*/
var $_models = [];
/**
* main() method. Update the counterCache on a provided model or all models
*
* @return bool|int|null Success or error code.
*/
public function main()
{
$this->out($this->getOptionParser()->help());
$model = $this->args[0];
if (!empty($model)) {
$this->loadModel($model);
$this->out(__('Updating CounterCache on {0}', $model));
$assoc = !empty($this->args[1]) ?? null;
$records = $this->{$model}->updateCounterCache($assoc);
$this->out("{$records} records updated");
} else {
foreach ($this->_models as $model) {
$this->loadModel($model);
$this->out(__('Updating CounterCache on {0}', $model));
$records = $this->{$model}->updateCounterCache();
$this->out("{$records} records updated");
}
}
}
/**
* Manage the available sub-commands along with their arguments and help
* @return \Cake\Console\ConsoleOptionParser
*/
public function getOptionParser()
{
$parser = parent::getOptionParser();
$parser->addArgument('model', [
'index' => 0,
'required' => false,
'help' => __('Provide a specific model to update')])
->addArgument('association', [
'index' => 1,
'required' => false,
'help' => __('Provide a specific association on the model'),
])->setDescription(__('Update all CounterCaches on all known Models. Adjust Models here: `\App\Shell\UpdateCounterCachesShell::$_models`'));
return $parser;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment