Execute a drush command programmatically | Drupal 8

Execute a drush command programmatically

Submitted by editor on Thu, 09/29/2016 - 15:49

How to execute a drush command programmatically ?


drush_invoke (For the current site)
drush_invoke($command, $arguments = array());

This creates a new process in a new Drupal instance. There for you must specify the site alias.
drush_invoke_process($site_alias_record, $command_name, $commandline_args = array(), $commandline_options = array(), $backend_options = TRUE);

Example 1. Enable a Module/Feature and Revert all features.

$site = drush_sitealias_get_record('@mysite');
drush_invoke_process($site, 'pm-enable', array("features_dependencies","-y"));
drush_invoke_process($site, 'features-revert-all', array("-y","--force"));

//OR for the current site:
drush_invoke_process('@self', 'features-revert-all', array("-y","--force"));


Example 2. Run a drush command at  the installation of a module. 

function mymodule_install() {
    // clears the 'all' cache for current web site
    //Methode 1.
    drush_invoke('cache-clear', 'all');

    $site = drush_sitealias_get_record('@mysite');
    drush_invoke_process($site, 'cache-clear', array('all'));

Add new comment