Paul M. Jones

Don't listen to the crowd, they say "jump."

Front-Interop: Interoperable Front Controller Interfaces

The front-interop project defines a set of interoperable interfaces for the FrontController pattern in PHP to encapsulate the request-receiving and response-sending behaviors at the outermost boundary of your HTTP presentation layer:

  • RequestHandler::handleRequest() : ResponseHandler encapsulates the logic to transform an incoming HTTP request to an outgoing HTTP response.

  • ResponseHandler::handleResponse() : void encapsulates the logic to send or emit an outgoing response.

These interfaces are completely independent of any particular request/response library. That is, they will work with PSR-7, Symfony HttpFoundation, Sapien, or any other request/response library.

Read more about the project here.

PHP-Styler 0.13.0 Released

PHP-Styler is a companion to PHP-Parser for reconstructing PHP code after it has been deconstructed into an abstract syntax tree.

I've done quite a bit with PHP-Styler since the last-announced 0.5.0 release a few weeks ago; the most important things are:

  1. Comment handling has been greatly improved, including greater fidelity regarding inline comments.
  2. There are now instructions on how to customize the Styler presentation.
  3. The demo site looks a lot nicer, and has a pretty good logo now.

Even though PHP-Styler is still in its 0.x release series, and is good enough for me to use on my own projects, it would benefit from wider usage to find edge cases. If you try out the Styler and find problems with it, please enter an issue!

Further, if you build a customized style, please let me know, and I can advertise it on the site.

PHP-Styler 0.5.0 Released

PHP-Styler is a companion to PHP-Parser for reconstructing PHP code after it has been deconstructed into an abstract syntax tree. As a pretty-printer for AST nodes, PHP-Styler will completely reformat your PHP code, discarding any previous formatting entirely. It will also split lines at idiomatically appropriate points for the given maximum line length, a feature I'm especially happy with.

Improvements and Additions

This release sees dramatic speed improvements (about 600% !) from the last-publicized 0.1.0 release, mostly from removing the php -l linting step in favor of using the error-checking from PHP-Parser. In addition, the code reassembly logic has been completely rewritten to use a Line object that splits into sub-Line objects, and applies splits to each Line independently. This results in a much more robust line-splitting process.

I have also added a bare-bones document on how to customize Styler output -- including notes on how to customize spacing around operators, and on opening-brace placement. If you have a coding style guide that you like, I invite you to try writing a customized Styler for it; I can advertise it on the PHP-Styler site.

And although you can use the preview command after installing PHP-Styler to safely preview any reformatting, I have put up a temporary online demonstration site -- type or paste in any PHP code to watch it get reformatted live. (As a side note, this gave me an excuse to try HTMX which really is quite easy to use.)

Line-Splitting Example

In testing the line-splitting logic, I applied PHP-Styler to several public codebases, including the HttpFoundation package from Symfony. Here is some original Symfony code before PHP-Styler gets hold of it:

class ExpressionRequestMatcher extends RequestMatcher
    // ...

    public function matches(): bool
        // ...

        return $this->language->evaluate($this->expression, [
            'request' => $request,
            'method' => $request->getMethod(),
            'path' => rawurldecode($request->getPathInfo()),
            'host' => $request->getHost(),
            'ip' => $request->getClientIp(),
            'attributes' => $request->attributes->all(),
        ]) && parent::matches($request);

Now to apply PHP-Styler. (The following is a simplified explanation of the line-splitting logic, looking just at the matches() return expression.)

In the first evolution of line-splitting, PHP-Styler begins by placing the entire statement on a single line with no splits at all.

        return $this->language->evaluate($this->expression, ['request' => $request, 'method' => $request->getMethod(), 'path' => rawurldecode($request->getPathInfo()), 'host' => $request->getHost(), 'ip' => $request->getClientIp(), 'attributes' => $request->attributes->all()]) && parent::matches($request);

Clearly this line is too long. PHP-Styler recognizes this and applies a second evolution to split lines at booleans:

        return $this->language->evaluate($this->expression, ['request' => $request, 'method' => $request->getMethod(), 'path' => rawurldecode($request->getPathInfo()), 'host' => $request->getHost(), 'ip' => $request->getClientIp(), 'attributes' => $request->attributes->all()])
            && parent::matches($request);

The boolean line is now within the limit, but the fluent method call above it is not. The third evolution applies an idiomatic member-operator split:

        return $this->language
            ->evaluate($this->expression, ['request' => $request, 'method' => $request->getMethod(), 'path' => rawurldecode($request->getPathInfo()), 'host' => $request->getHost(), 'ip' => $request->getClientIp(), 'attributes' => $request->attributes->all()])
            && parent::matches($request);

The $language property stays with $this, but the evaluate() method call gets split -- even then, the line remains too long. The fourth evolution applies an argument split on that line:

        return $this->language
                ['request' => $request, 'method' => $request->getMethod(), 'path' => rawurldecode($request->getPathInfo()), 'host' => $request->getHost(), 'ip' => $request->getClientIp(), 'attributes' => $request->attributes->all()]
            && parent::matches($request);

Now the arguments are split out to their own lines and indented; the only remaining over-long line is the second argument. The fifth evolution applies an array split:

        return $this->language
                    'request' => $request,
                    'method' => $request->getMethod(),
                    'path' => rawurldecode($request->getPathInfo()),
                    'host' => $request->getHost(),
                    'ip' => $request->getClientIp(),
                    'attributes' => $request->attributes->all()
            && parent::matches($request);

Now that the array argument has been split and indented, all of the lines are within the limit, and PHP-Styler moves on to the next chunk of code.

As we can see, the end result is similar but not identical to the original Symfony code. Still, the PHP-Styler presentation is arguably a reasonable alternative to the original.

What's important here is that no matter the style of the original code, the restyled code will always end up the same way. The original code could be an absolute mess, but PHP-Styler will present it coherently regardless. All style decisions will look like they have been made by a single mind, granting at least one aspect of consistency and coherence to any codebase.


There's still more to be done with PHP-Styler, such as adding annotations to ignore a file for styling, or to force array expansion across lines. Inline comments present some problems, as does variable interpolation into double-quoted strings with newlines. Unfortunately, those are because of how the upstream PHP-Parser works, so I'll have to report those and hope for a solution there.

Even so, PHP-Styler is good enough for my own projects now, and I'm happy to have spent the time working it up.

Teller: Money for Legacy Applications in PHP

I am happy to say that MoneyPHP 4.2.0 incorporates my Teller contribution for handling monetary math in legacy codebases.

Legacy codebases often use float math for monetary calculations, which leads to problems with fractions-of-pennies in monetary amounts. The proper solution is to introduce a Money object, and use Money objects in place of float math. However, doing so can be quite a hardship, especially when the float values need to be moved to and from database storage. Intercepting and converting the float values (often represented by strings) into Money objects on their way out of the database, then reconverting them to their original format on their way back to the database, can be very difficult and time-consuming.

To help ease the transition from float math to Money objects, use a Teller instance to replace float math for monetary calculations in place. Without Teller, your math might look like this ...

$price = 234.56;
$discount = 0.05;
$discountAmount = $price * $discount;
// => 11.728

... and you end up with an extraneous $0.008. Whereas with Teller, you can replace the money math in place, without needing to create Money objects:

// create a Teller, perhaps in a DI container ...
$teller = \Money\Teller::USD();

// ... then use it for monetary math:
$price = 234.56;
$discount = 0.05;
$discountAmount = $teller->multiply($price, $discount);
// => '11.73'

The main drawback is that you cannot use two different currencies with the Teller; you can use only one.

Teller supports the full range of Money operations. You can read the documentation for it here.

There Is Only One Science

"All science is either physics or stamp-collecting."

-- Ernest Rutherford

I recall hearing it first another way, I think via Heinlein: "There is only one science. It is called 'physics.' Everything else is stamp-collecting." I like that phrasing better, because it highlights the disparity more plainly.

Anything that calls itself "science" must be based on observation, but only physics provides a predictive capacity from those observations. The other "sciences" consist only of collections of observations; those observations can be categorized, organized, and reorganized as new observations are collected, but they do not provide a predictive capacity. They do not tell you what your next observation will be with much certainty. If you find a strongly predictive capacity, chances are that there is a physics component underlying the observations.

Thus, the further you get from "physics", the further you get from "science."

Introducing PHP-Styler

PHP-Styler is a companion to PHP-Parser for reconstructing PHP code after it has been deconstructed into an abstract syntax tree. As an alternative to the pretty-printer bundled with PHP-Parser, it supports:

  • configurable line-length, line-ending, and indent-string
  • automatic indenting and line breaks
  • automatic splitting of "too-long" lines
  • programmable/customizable styling

PHP-Styler is not a coding style "fixer" per se. Instead, it will completely rebuild PHP code from the AST, applying its style rules along the way. The result is a consistent formatting style, regardless of the original formatting.

Whereas something like PHP-CS-Fixer has scores of configuration parameters, PHP-Styler gives you imperative control over its output. Extend the default Styler implementation with your own overrides to change where braces go, to place or remove the space after ! conditions, whether or not if/elseif/else should be on separate lines, and so on.

I'm especially happy with the line-splitting logic. PHP-Styler begins by building one statement per line, but if the line is too long, it follows an incremental set of rules to split that line into shorter readable parts.

There are still some outstanding formatting issues around closures and comments, but I have smoke-tested PHP-Styler against several codebases besides my own, and I found the results surprisingly acceptable (not perfect, but unexpectedly good). It's certainly good enough for my own projects, though it did reveal some of my own preferences that I was not aware of, as well as some inconsistencies in my own style choices.

If you are using PHP-Parser and want a better pretty-printer, or if you have been looking for an alternative to PHP-CS-Fixer, give PHP-Styler a try!

Qiq Tags and PHP Tokens

I released Qiq 2.1.0 last week, with a new feature made possible only by using PHP tokens during the Qiq compiling process.


Qiq is a template system for PHP. It uses native <?php ... ?> for the template syntax, but it allows for using a Qiq {{ ... }} syntax as well. Qiq syntax is the same as PHP, with a light dusting of syntax sugar added to make it more concise. That means a helper call in Qiq syntax ...

{{= anchor('') }}

... gets $this-> added to it when Qiq compiles it to PHP ...

<?= $this->anchor('') ?>

... making helper usage more concise in Qiq. It also means you can mix PHP in with Qiq as much or as little as you like, because Qiq code is pretty much just PHP code.


One thing which always irked me a bit was that if you use a helper under Qiq syntax, but not as the opening keyword, you would still need to use $this-> inside the Qiq tags. For example, the following variable assignment would generate an error ...

{{ $a = anchor('') }}

... because the compiler looked only at the opening keyword, and did not know to add $this-> to the anchor() call. Instead, if you were past the first keyword, you would have to add $this-> yourself:

{{ $a = $this->anchor('') }}

That adds a bit of cognitive friction, but it didn't bother me too much, until someone else brought it up.


Having a real bug report/feature request motivated me to address the issue. The problem was, how could the Qiq compiler examine the remaining code inside the Qiq tags, look for words that qualify as function calls, and add $this-> to them?

My first thought was to bring in nikic/php-parser and use it as part of a secondary compiling process. The idea was to convert the Qiq {{ ... }} syntax to PHP first, then run that PHP code through php-parser, find all plain function calls, and add $this-> to them.

That turned out to be more difficult than I thought it would be; walking the AST properly involved more effort than I would have liked for this endeavor. In addition, the php-parser pretty-printer for generating the converted output did not look suited to this particular task. I want very much for the Qiq code and the resulting PHP code to match up very closely, and the pretty-printer cannot guarantee that at this point.


As a result, I decided to fall back to the plain old PhpToken functionality (it's an improved version of token_get_all()). This turned out to be much more applicable to the problem at hand. The Qiq compiler process doesn't need a full AST as provided by php-parser, it just needs identify function calls.

Using an extended php token class, the Qiq compiler can tokenize the Qiq-enclosed PHP code, then examine each token to see if it looks like a function call. It does this by ...

  • checking that the current token is a non-keyword non-encapsed string;
  • looking ahead to see if the next significant token is an opening parenthesis;
  • and looking back to make sure the previous significant token is not ->, ?->, ::, or the function keyword.

Under those conditions, the current token is presumed to be a function call, and the compiler adds $this-> to it. (It's possible that these conditions might need some improvement, but testing on existing templates did not reveal any trouble.)

This approach took some trial-and-error, but the resulting solution is only 70 lines of code, and well-targeted to the problem at hand.


As a result, you can now use a helper anywhere inside Qiq {{ ... }} tags, without having to add $this-> yourself. That means the Qiq code from the opening example now assigns the variable without error ...

{{ $a = anchor('') }}

... which eliminates the last little bit of cognitive friction I have felt with Qiq.

Many thanks to apple-x-co for submitting the report that motivated this improvement!


Try Qiq for your template system, because you like PHP syntax, but you also want:

  • Concise, explicit, context-specific escaping
  • Views, layouts, and partials
  • Blocks and inheritance
  • Rich and extensible HTML helpers
  • Easy-to-implement static analysis
  • Full documentation and unit-testing

AutoShell 1.0 Released

I am proud to announce the first release of AutoShell, a library for building CLI commands in PHP 8.1 and up.

Just as with AutoRoute for web routing, AutoShell automatically maps CLI command names to PHP command classes in a specified namespace. For example, given a namespace of Project\Cli\Command, the CLI command name create-article automatically maps to the Project\Cli\Command\CreateArticle command class.

AutoShell is low-maintenance. Merely adding a class to your source code, in the recognized namespace and with the recognized main method name, automatically makes it available as a command.

AutoShell will automatically map command-line arguments to the command class main method parameters. For example, given this command class ...

namespace Project\Cli\Command;

use AutoShell\Help;

#[Help("Says hello to a _name_ of your choice.")]
class Hello
    public function __invoke(

        #[Help("The _name_ to say hello to.")]
        string $name

    ) : int
        echo "Hello {$name}" . PHP_EOL;
        return 0;

... AutoShell will recognize php bin/console.php hello world and output Hello world.

And as you can see, help is defined via attributes. Options are easy to define, too -- as is combining common option sets with command-specific ones.

There's a lot more to AutoShell; take a look at the documentation to get started!

You can read the Reddit discussion about this post here.

Qiq Templates 2.0 Released

I am happy to annouce the 2.0 release of Qiq templates for PHP 8.

Qiq is for developers who prefer native PHP templates, but with less verbosity. It offers:

This release incorporates several substantial changes; you can see the upgrade notes here.

The most important of these changes is that Qiq templates are now easily subject to static analysis. Add a docblock typehint for $this in your template files, recompile any templates using Qiq syntax, and run your static analyzer against your templates. Yes, it's that easy.

The way helpers are implemented has also changed. Previously, you would have to register your helper class with a helper locator, but that made static analysis more difficult. As of this release, helpers are now just methods on a Helpers class, which makes static analysis simple and straightforward. To add a helper, extend the Helpers class and write any method you like. In addition, all helper objects are retained in a PSR-11 container object; use the lightweight Container provided by Qiq, or bring your own (maybe Capsule).

Finally, a Twig-like implementation of "blocks" and "inheritance" has been added to this release, and backported to the latest 1.x release.

If you're a Twig user looking to branch out, or if you like native PHP templates but want something a little more concise, try Qiq!