pogo: Run PHP scripts with inline dependencies
Pogo allows you to write small PHP scripts which use PHP libraries (courtesy
packagist)... but it doesn't require you setup a
special-purpose folder, project, or repository. To use a dependency, simply
add a small pragma into your script. This makes it easier to use PHP
- Experimenting or learning
- Writing random system-automation scripts and one-off scripts
Let's pick a small task that requires a few libraries -- suppose we want
to generate a pretty PDF from a source-code file (
We'll need a pretty-printer (scrivo/highlight.php)
and a PDF generator (dompdf/dompdf).
Skimming the README for each library, one finds a few introductory snippets.
I took these, added the
#!require pragmas, and improvised a little on the
$html variable. This becomes a small script,
<?php $code = file_get_contents('php://stdin'); #!require scrivo/highlight.php: ~9.15 $hl = new \Highlight\Highlighter(); $hl->setAutodetectLanguages(['php', 'css', 'yaml', 'json', 'js']); $highlighted = $hl->highlightAuto($code); $html = sprintf('<link rel="stylesheet" href="file://%s"/>', \HighlightUtilities\getStyleSheetPath('sunburst.css')); $html .= sprintf("<pre><code class=\"hljs %s\">%s</code></pre>", $highlighted->language, $highlighted->value); #!require dompdf/dompdf: ~0.8.3 $dompdf = new \Dompdf\Dompdf(); $dompdf->loadHtml($html); $dompdf->setPaper('A4', 'landscape'); $dompdf->render(); $dompdf->stream();
To run this script in the CLI, just use:
Of course, this script expects some content as input (e.g.
myfile.yml) and produces a PDF as output (e.g.
myfile.pdf), so a more realistic command would be
cat myfile.yml | pogo code2pdf.php > myfile.pdf
Most of my day-to-day work is in PHP, JS, and bash. From time-to-time, one needs a bit of glue-code for one-offs, and
I find myself avoiding PHP for that task... because using a library in PHP still requires bits of administrativa.
pogo is an experiment to reduce that administrativa. Just create a
.php file and run it.