Magento 2: programmatically run setup upgrade
To do so you need to use the Magento/Setup/Model/InstallerFactory
class.
For example this is the code that runs when you call the CLI command:
$keepGenerated = $input->getOption(self::INPUT_KEY_KEEP_GENERATED);
$installer = $this->installerFactory->create(new ConsoleLogger($output));
$installer->updateModulesSequence($keepGenerated);
$installer->installSchema();
$installer->installDataFixtures();
if (!$keepGenerated) {
$output->writeln('<info>Please re-run Magento compile command</info>');
}
<?php
use Magento\Framework\App\Bootstrap;
include('../app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$modules = array('VENDORNAME_MODULENAME');
try{
/* Code to enable a module [ php bin/magento module:enable VENDORNAME_MODULENAME ] */
$moduleStatus = $objectManager->create('Magento\Framework\Module\Status')->setIsEnabled(true,$modules);
/* Code to run setup upgrade [ php bin/magento setup:upgrade ] */
$installerFactory = $objectManager->create('Magento\Setup\Test\Unit\Console\Command\UpgradeCommandTest')->testExecute();
/* Code to clean cache [ php bin/magento:cache:clean ] */
try{
$_cacheTypeList = $objectManager->create('Magento\Framework\App\Cache\TypeListInterface');
$_cacheFrontendPool = $objectManager->create('Magento\Framework\App\Cache\Frontend\Pool');
$types = array('config','layout','block_html','collections','reflection','db_ddl','eav','config_integration','config_integration_api','full_page','translate','config_webservice');
foreach ($types as $type) {
$_cacheTypeList->cleanType($type);
}
foreach ($_cacheFrontendPool as $cacheFrontend) {
$cacheFrontend->getBackend()->clean();
}
}catch(Exception $e){
echo $msg = 'Error during cache clean: '.$e->getMessage();die();
}
}catch(Exception $e){
echo $msg = 'Error during module enabling : '.$e->getMessage();die();
}