Skip to content

Instantly share code, notes, and snippets.

@vdubyna
Created July 11, 2018 16:04
Show Gist options
  • Save vdubyna/792f9a2c796443f33f0a563f1dad2d7b to your computer and use it in GitHub Desktop.
Save vdubyna/792f9a2c796443f33f0a563f1dad2d7b to your computer and use it in GitHub Desktop.
Run Magento 2 code in console
#!/usr/bin/env php
<?php
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Application;
if (PHP_SAPI !== 'cli') {
echo 'dev/run-script.php must be run as a CLI application';
exit(1);
}
try {
require __DIR__ . '/../app/bootstrap.php';
} catch (\Exception $e) {
echo 'Autoload error: ' . $e->getMessage();
exit(1);
}
class RunScriptCommand extends Command
{
/** @var \Magento\Framework\DB\Adapter\Pdo\Mysql */
protected $connection;
protected function configure()
{
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, []);
$objectManager = $bootstrap->getObjectManager();
$this->connection = $objectManager->get('Magento\Framework\App\ResourceConnection')
->getConnection();
$this
->setName('dev:run-script')
->setDescription('Run script');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln("Run script");
// Run sql queries
//$rows = $this->connection->fetchAll($sql);
// Load order
//$order = $this->objectManager->create('Magento\Sales\Model\Order');
//$order->loadByIncrementId($orderNumber);
}
}
try {
$handler = new \Magento\Framework\App\ErrorHandler();
set_error_handler([$handler, 'handler']);
$application = new Application();
$application->add(new RunScriptCommand());
$application->run();
} catch (\Exception $e) {
while ($e) {
echo $e->getMessage();
echo $e->getTraceAsString();
echo "\n\n";
$e = $e->getPrevious();
}
exit(\Magento\Framework\Console\Cli::RETURN_FAILURE);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment