You can build a magento script as a magento command class and execute it inside the var folder.
It’s useful when you need to run quickly a magento command without building a module and deploying.
Base example
Redefine a simple magento cli including a magento (symfony) command class:
mkdir -p var/scripts/commands
tee var/scripts/magento <<'EOF'
#!/usr/bin/env php
<?php
require __DIR__ . '/../../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$application = new Magento\Framework\Console\Cli('Magento CLI');
require(__DIR__.'/commands/MyCommand.php'); // or insert your class here
$application->add($objectManager->get('MyCommand'));
$application->run();
EOF
chmod +x var/scripts/magento
Then run the new magento cli command with MyCommand
included:
./var/scripts/magento
Scan command directory
Define a new magento cli which automatically reads new commands taken from a specific folder var/scripts/commands
and extracts their namespaces:
mkdir -p var/scripts/commands
tee var/scripts/magento <<'EOF'
#!/usr/bin/env php
<?php
require __DIR__ . '/../../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$application = new Magento\Framework\Console\Cli('Magento CLI');
$files = glob(__DIR__.'/commands/*.php');
$m=[];
foreach ($files as $file) {
require($file);
$className=pathinfo($file, PATHINFO_FILENAME);
if(preg_match_all('/namespace\s*([^;]*)/',file_get_contents($file),$m, PREG_PATTERN_ORDER)) {
$className = ($m[1][0]??'').'\\'.$className;
}
$application->add($objectManager->get($className));
}
$application->run();
EOF
chmod +x var/scripts/magento
Save your commands classes in var/scripts/commands/
.
Then run the magento cli with including your new commands:
./var/scripts/magento
For example:
wget https://raw.githubusercontent.com/fvanzani/module-eavcleaner-m2/refs/heads/main/Console/Command/RemoveUnusedMediaCommand.php -O var/scripts/commands/RemoveUnusedMediaCommand.php
./var/scripts/magento eav:media:remove-unused -c -r --dry-run
Leave a Reply