<p>Since Yii treats console commands like requests, you need to perform the following steps to execute a Craft console command from within a plugin:</p>

<ol>
<li>Within your plugin, set the namespace to match the commands namespace</li>
<li>Call a run action from your plugin, and pass the route name/params</li>
</ol>

<pre><code>    MyPlugin::$plugin-&gt;getInstance()-&gt;controllerNamespace = 'craft\console\controllers';

    $command = MyPlugin::$plugin-&gt;getInstance()-&gt;runAction('gc/run');
</code></pre>

CC BY-SA 4.0
2019-10-14T01:55:50.850Z
2019-10-14T18:35:31.850Z
2019-10-14T18:35:31.850Z
Jason McCallister
<p>I am in the process of building a plugin that has a controller that accepts a HTTP request. If the token and request are valid, I would like to call a Craft Console Command from within the plugin (e.g. <code>gc/run</code> or <code>resave/entries</code>).</p>

<p>The equivalent would be using the CLI for call the command <code>./craft gc/run</code> but from a controller.</p>

<p>How would I call the command from my plugins HTTP controller?</p>

CC BY-SA 4.0
2019-10-12T06:17:02.703Z
Do you need to call some build in command or your own? Usually I wrap functions in Service Classes so I can call them both from controllers and/or console commands.
naboovalley
CC BY-SA 4.0
2019-10-12T11:57:44.330Z
I’m calling a built in command. Running in a Docker environment so I cannot SSH into the machine.
Jason McCallister
<plugin-development><craft3><plugins><request><console>
Calling Craft Console Commands from Plugin?
# Calling Craft Console Commands from Plugin?

(Asked by: username_0 on 2019-10-11)

I am in the process of building a plugin that has a controller that accepts a HTTP request. If the token and request are valid, I would like to call a Craft Console Command from within the plugin (e.g. `gc/run` or `resave/entries`).

The equivalent would be using the CLI for call the command `./craft gc/run` but from a controller.

How would I call the command from my plugins HTTP controller?

**Tags:** plugin-development, craft3, plugins, request, console
> **Comments:**
> **username_1**: Do you need to call some build in command or your own? Usually I wrap functions in Service Classes so I can call them both from controllers and/or console commands.  
> **username_0**: I’m calling a built in command. Running in a Docker environment so I cannot SSH into the machine.  

---

## 1 answers

### Answer by username_0 on 2019-10-14. Score: 1 | Accepted answer

Since Yii treats console commands like requests, you need to perform the following steps to execute a Craft console command from within a plugin:

Within your plugin, set the namespace to match the commands namespace
Call a run action from your plugin, and pass the route name/params

    MyPlugin::$plugin->getInstance()->controllerNamespace = 'craft\console\controllers';

    $command = MyPlugin::$plugin->getInstance()->runAction('gc/run');


---

