Using Prettier in PHP

Back-end, Front-end

Using Prettier in PHP

Maxime Fabre

Maxime Fabre

What is Prettier?

Originally from the Javascript ecosystem, Prettier is a code formatter which means it takes your code and makes it – as its name suggests – prettier. There are code formatters for many languages; even Javascript has quite a few of them.

Prettier, however, is currently one of the most popular code formatters out there, and it has spread to a lot of different languages already for one simple reason: it gives zero fucks about how you think your code should be formatted. You can pass a few basic options to Prettier (indentation, max width, the basics) but other than that it takes your whole code and reformats it from scratch, disregarding any formatting decision you may have previously taken.


This may sound counter-intuitive but it tremendously reduces friction when writing code. The more you trust Prettier, the more you can stop worrying about formatting altogether. You can type code in one disgusting line, press save, and the result is nicely formatted code. You stop thinking about indentation, manually adding commas, or placing things for maximum readability and such. These distractions take up much more of your day than people realise because those are micro interruptions that are scattered and as such feel inconsequential. Once you go without them though, you will realise how much time they take up.

Prettier and PHP

So ok, Javascript and a bunch of other front-end languages (CSS, HTML, GraphQL, etc.) have this tool, but this is Serious Enterprise PHP™ we have Serious Enterprise Tools™ to take care of our code style and PSRs and RFCs and all that – we don’t just type code until it’s pretty. What is this? Ruby?

At madewithlove we currently use (mainly but not only) PHP CS Fixer. However, a glance at the list of the things it fixes shines a light on the main reason I still use Prettier in addition to it. PCS conflates code format (how the code is formatted, how pretty it is) and coding style (how the code is written, how good it is). Most of the time, it will fix the latter, in very PHP specific ways, but will do very little for the former besides a few blank lines and indentation rules.

How do you use Prettier?

Most of the time Prettier would be added to the project’s package.json, but since we want to use it in a PHP project we’ll install it globally through NPM (or Yarn if you want).
Next, as the PHP support is not yet stable, we’ll have to add that functionality into Prettier specifically:

npm install --global prettier @prettier/plugin-php

Once Prettier is installed, you can quickly try it out on one or more files by invoking it directly (e.g. prettier somefile.php or prettier src/**.php). An example with some badly formatted code:

<?php
namespace Foobar;
    class SomeClass    {
            public   function getCallbacks() {
            return        array( function () {return $this->firstName;},
            function () {
                return $this->callSomeMethod('foo')->andThenOtherMethod( Bar::withSome("arguments"),
                    $andShit                );
});
}}

If you run prettier bad.php it will return the formatted code. You could then pass the --write option to write the result directly to the file. The results:

<?php
namespace Foobar;

class SomeClass
{
    public function getCallbacks()
    {
        return array(
            function () {
                return $this->firstName;
            },
            function () {
                return $this->callSomeMethod('foo')->andThenOtherMethod(
                    Bar::withSome("arguments"),
                    $andShit
                );
            }
        );
    }
}

Where it gets interesting is that because Prettier rewrites the code, it continually adapts. If there were a third method call or if the configured max width was different, it would format the code differently. This is a key difference with the formatting PHPStorm or PCS would give you because they follow very consistent rules: how to break down arguments, methods, classes, et al depending on their width, etc.

Prettier doesn’t do that when it formats the code; it barely even knows that it is formatting PHP code because it purely translates the input into an abstract tree and formats it based on how readable it expects the output to be. It doesn’t fully know what it is formatting, just where it can add breaks and newlines.

So you might disagree with the final output file, but that would be missing the point which is to stop caring about whether you agree or disagree in the first place.

How do you use it without having to type shit in the terminal?

Because Prettier is such a widely adopted tool, wherever Prettier is supported you can use it to format PHP code there – as long as it correctly uses the prettier where you’ve installed @prettier/plugin-php. However because we often follow some Symfony rules that would clash with the way Prettier reformats, since it does so according to PSR2, I instead recommend to add Prettier to your pre-commit pipeline/CI/etc. Reformat on save and on commit aren’t incompatible , but the latter is the safest way.

You can use various tools for that, such as GrumPHP, but the most straightforward way remains the following to your composer.json file:

"scripts": {
    "fix-cs": ["prettier src/**/* --write", "php-cs-fixer fix"]
}

And then you can run it with composer fix-cs. Be careful, however, that while Prettier is very fast to run, PCS takes a lot more time, so keep the formatting on save for Prettier.

That doesn’t look worth it at all

Okay, so it reformats a few lines, PHPStorm can also do that without adding another tool.

Saying “Prettier just reformats code” would be very reductive and it would be ignoring the pros that it brings on its own.

  1. Using Prettier speeds up the time spent writing code by a huge factor. I talked about this a bit before but it’s not just the time spent formatting your code that is lost right now; it’s the time spent even thinking about it. What is the most readable way to split these lines? How can I best carefully arrange these characters so that they’re easy to read? It’s a whole mental load that suddenly goes away, and you never look back.
  2. Prettier is insanely fast, almost instantaneously fast. Comparing it to tools like PCS or PCF is night and day because they’re not even booted by the time Prettier is done formatting your code, which is why the whole “format on save” paradigm is so important here compared to other tools.
  3. It also supports a shitload of languages: once you’re used to letting Prettier reformat your code you can let it loose on a massive chunk of your codebase. The website lists the supported languages, but it’s simple to set up a command such as: prettier '{src/**,.}/*.{js,php,md,json,yml}' which formats most files in your codebase including READMEs and fixture files. It even knows how to write YAML files correctly, a piece of knowledge long lost in the Symfony Wars of 2009.

Is it ready yet?

Prettier inherently changes the way you code, and it is coming to many more languages other than PHP (e.g. Python, Ruby). In the span of a few months, Prettier almost single-handedly ended most formatting wars happening in the JS ecosystem; people went from entire tirades about trailing semicolons to #justuseprettier.

Although the PHP plugin is not released to the public yet, I am very much excited for when it will be and to see if it has the same effect on its community, even in a smaller way. I think the PHP community has spent literal decades arguing on how to format code, to the point we needed a whole committee to regulate on it. I think it’s time we as developers get over this and start letting tools do these menial inconsequential tasks that we should have delegated to them entirely by now.

So stop worrying about whether to put this brace on this line or the next, about whether you should put spaces around parentheses or anything like that for that matter. Just write your code, and let Prettier (or another tool) worry about the rest because no one is scouring the market for people who are an expert at neatly arranging braces. That’s not your job.

“But the code would have been more readable had the argument been on a separate li–
I know, it’s ok. Prettier will get better, it continually does. But I repeat: this is not your job.

Hire Maxime as a speaker?

Hire Maxime as a speaker?
Maxime Fabre

Maxime Fabre

Maxime is madewithlove’s ‘French Connection’. He’s our (only) software engineer that speaks French fluently, thanks to being born and raised in the land of berets and baguettes. What else makes Maxime unique? His highly developed sense of how code should look and feel… which makes him a much appreciated colleague and ditto member of the Laravel/PHP community. As for his penchant for chocolate biscuits with soya sauce and mayonnaise, there’s no accounting for personal taste.

our blog Related blog articles

Do you have a question? Leave a comment