# **Chapter 21: ConsoleGate — Running Gates From the Command Line**
> **Prerequisites:** Chapters 1-3 (Gates and events)
> **Try it:** Tested code from gate `ex13console`
> (`apps/examples/Ex13console.gate.php`). Run from the project root:
>
> ```bat
> php -f start.php -- --gate ex13console --evt help
> ```
---
## **21.1 A Gate Without a Browser**
`ConsoleGate` (`\Sphp\Gates\ConsoleGate`) is the same event system —
`onstart`, `page_new`, `page_event_*` — driven by CLI arguments instead of a
URL. Same `reg.php` registration, same routing, different output channel.
Use cases: cron jobs, importers, queue workers, deploy scripts, and shell
command runners — all written as Gates, testable like Gates.
## **21.2 The Tested Demo Gate**
```php
<?php
// apps/examples/Ex13console.gate.php (tested)
class Ex13console extends \Sphp\Gates\ConsoleGate
{
/** Demo commands shared with Ex14 NativeGate UI */
public static $demoCmds = array(
'php -v',
'echo SartajPhp-shell-ok',
'python -c "print(2+2)"',
);
public function onstart()
{
$this->enableStdout(); // print output to the terminal
}
public function page_new()
{
$this->printHelp(); // no --evt → page_new runs
}
public function page_event_help($evtp)
{
$this->printHelp();
}
public function page_event_demos($evtp)
{
$this->sendMsg('=== ConsoleGate demos ===');
foreach (self::$demoCmds as $cmd) {
$this->runOne($cmd);
}
$this->sendMsg('=== done ===');
}
/** --evt run --evtp "cmd here" OR --evt run --cmd "cmd here" */
public function page_event_run($evtp)
{
$cmd = trim((string) $evtp);
if ($cmd === '') {
$cmd = trim((string) $this->consoleReadArgument('--cmd'));
}
if ($cmd === '') {
$this->sendMsg('Missing command. Use --evtp or --cmd', 'e');
return;
}
$this->runOne($cmd);
}
private function runOne($cmd)
{
$this->sendMsg('> ' . $cmd);
$out = '';
$ok = $this->callSync($cmd, $out, 'shell'); // run OS command, capture stdout
$text = trim((string) $out);
if ($text !== '') {
$this->consoleWriteln($text);
}
$this->sendMsg($ok ? '[exit ok]' : '[exit fail]', $ok ? 'i' : 'e');
}
}
```
## **21.3 The CLI Contract**
```
php -f start.php -- --gate <gate> --evt <event> --evtp <parameter> [--custom value]
```
| Argument | Maps to |
|----------|---------|
| `--gate ex13console` | registered gate name (`reg.php`) |
| `--evt help` | `page_event_help($evtp)` |
| `--evtp "php -v"` | the `$evtp` parameter |
| `--cmd "echo hello"` | custom flag — read with `consoleReadArgument('--cmd')` |
| *(no `--evt`)* | `page_new()` |
Verified output on this machine:
```
> php -v
PHP 8.x ...
[exit ok]
> echo SartajPhp-shell-ok
SartajPhp-shell-ok
[exit ok]
```
## **21.4 ConsoleGate API Used Here**
| Call | Effect |
|------|--------|
| `enableStdout()` (in `onstart`) | write messages to the terminal |
| `sendMsg($text, $type)` | message line (`'i'` info, `'e'` error, `'w'` warn) |
| `consoleWriteln($text)` | raw line to stdout |
| `consoleReadArgument('--flag')` | read extra CLI arguments |
| `callSync($cmd, &$out, $label)` | run an OS command, capture output, bool success |
`callSync` is inherited by NativeGate too (Chapter 22) — one API for shell
work whether the Gate runs in a terminal, a WebSocket server, or a Cloud app.
## **21.5 Writing Real Console Gates**
A cron-style importer keeps the same shape:
```php
<?php
class ImportGate extends \Sphp\Gates\ConsoleGate
{
public function onstart() { $this->enableStdout(); }
/** php -f start.php -- --gate import --evt csv --evtp "data/orders.csv" */
public function page_event_csv($evtp)
{
$file = (string) $evtp;
if (!is_file($file)) {
$this->sendMsg('No such file: ' . $file, 'e');
return;
}
$db = SphpBase::dbEngine(); // same dbEngine as web Gates
$db->connect();
// ... insert rows via $db->insertSql($frm, 'orders') ...
$db->disconnect();
$this->sendMsg('Import done');
}
}
```
Notes:
1. **Everything else is normal** — `reg.php`, `comp.php`, dbEngine, helpers,
`SphpBase` APIs all work identically
2. **No sessions/permissions UI** — authenticate by convention (run as a
system user; keep secrets in `comp.php`)
3. **Windows scheduler / cron** call the same command line; exit reflects
success/failure for scripting
4. **Debugging**: `debugMode` traces still go to stdout — Chapter 19 applies
## **21.6 Verify It Yourself**
From `d:\www\SartajPhpDoc`:
```bat
php -f start.php -- --gate ex13console --evt help
php -f start.php -- --gate ex13console --evt demos
php -f start.php -- --gate ex13console --evt run --evtp "php -v"
php -f start.php -- --gate ex13console --evt run --cmd "echo hello"
```
Expected: help text, three demo commands with `[exit ok]`, and the single
command echoes.
---
**Previous:** [Chapter 20 — Output Cache](chapter20.md) ·
**Next:** [Chapter 22 — NativeGate: WebSocket Apps and Child Processes](chapter22.md)