Execute a drush command programmatically | Drupal 8

Execute a drush command programmatically

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

How to execute a drush command programmatically ?

Methodes:

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

drush_invoke_process
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');
    
    Or

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

Comments

Anonymous (not verified)

Wed, 03/21/2018 - 15:31

In reply to by Insasse (not verified)

You have to us drush_invoke_process() becaus drush_invoke() doesn't exist anymore -> https://github.com/drush-ops/drush/blob/master/includes/command.inc

Rifas (not verified)

Mon, 09/17/2018 - 07:55

Saying drush_invoke function is not defined

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.