Getting startedA first project

Getting started

A first project

From an empty directory to a class written in Phaenon, compiled, autoloaded by Composer, tested with PHPUnit and analysed with PHPStan.

This page builds a small project from nothing: one class written in Phaenon, checked, compiled into the PHP that Composer autoloads, tested with PHPUnit and analysed with PHPStan. You need PHP 8.5 and Composer; every step is a command you run in an empty directory.

The project

Start with a composer.json whose autoloader points at .src/:

composer.json
{
    "name": "acme/hello",
    "type": "project",
    "require": {
        "php": ">=8.5"
    },
    "autoload": {
        "psr-4": {
            "App\\": ".src/"
        }
    }
}

You write the sources in src/. phn build writes the PHP into .src/, and everything that runs or reads PHP, Composer's autoloader, PHPUnit, PHPStan, points there. The .src/ directory sits beside src/ at the same depth, so a compiled file's __DIR__ resolves to the same places its source would: __DIR__ . '/../config' still finds config/.

require.php is also the project's target, the oldest PHP the compiled code must run on: here PHP 8.5.

Then add the compiler, as Install explains:

composer config allow-plugins.phaenon/phn true
composer require phaenon/phn

phaenon.json

The project file names the directories that hold sources and the directory each compiles into:

phaenon.json
{"roots": {"src": ".src"}}

That is all a project needs. phaenon.json lists the other keys, such as "php" to state the target in the file instead.

A class

A .phn file is PHP without the <?php tag. Put this in src/Greeter.phn:

src/Greeter.phnyou write
namespace App;

final class Greeter
{
    __construct(private string $greeting = 'Hello') {}

    /** One line per name, in the order given. */
    greet(list<string> $names): list<string> {
        return array_map(fn (string $name): string => "{$this->greeting}, {$name}!", $names);
    }
}
.src/Greeter.phpphn build writes
<?php

/* @generated by phaenon from Greeter.phn */

declare(strict_types=1);

namespace App;

final class Greeter
{
    public function __construct(private string $greeting = 'Hello') {}

    /**
     * One line per name, in the order given.
     * @param list<string> $names
     * @return list<string>
     */
    public function greet(array $names): array
    {
        return array_map(fn (string $name): string => "{$this->greeting}, {$name}!", $names);
    }
}

Two things differ from the PHP you would write. A method is declared without function, and is public unless it says otherwise. list<string> is a type of the language: in the PHP it becomes array in the signature and list<string> in the docblock, where PHPStan and PhpStorm read it. The compiled file ends with one more line than shown here, a comment that maps its lines back to the .phn; Line maps and debugging explains it.

Check, build, run

phn check type-checks the project's roots and writes nothing:

vendor/bin/phn check
1 files checked: 0 errors, 0 warnings

phn build checks too, then writes the outputs:

vendor/bin/phn build
1 files compiled, 1 written, 0 files copied, 0 stale outputs removed

The class now loads like any other:

php -r 'require "vendor/autoload.php"; echo implode("\n", (new App\Greeter())->greet(["Ada", "Linus"])), "\n";'
Hello, Ada!
Hello, Linus!

You rarely run phn build by hand. The plugin builds whenever Composer writes the autoloader, so an install, an update or a dump brings the outputs up to date:

rm -rf .src
composer dump-autoload
Generating autoload files
> phn build
1 files compiled, 1 written, 0 files copied, 0 stale outputs removed
Generated autoload files

What to commit

Commit the sources and the project files: composer.json, composer.lock, phaenon.json, src/. Ignore the outputs, which every install rebuilds:

.gitignore
/vendor/
/.src/
/.tests/

composer.lock pins phaenon/phn, and the package pins the binary by its checksum, so a fresh clone compiles with the same compiler and gets the same PHP, byte for byte.

Tests with PHPUnit

Tests are a second root. Add it to phaenon.json:

phaenon.json
{"roots": {"src": ".src", "tests": ".tests"}}

Point the autoloader's development entry at its output, in composer.json:

"autoload-dev": {
    "psr-4": {
        "App\\Tests\\": ".tests/"
    }
}

Write the test in tests/GreeterTest.phn:

tests/GreeterTest.phn
namespace App\Tests;

use App\Greeter;
use PHPUnit\Framework\TestCase;

final class GreeterTest extends TestCase
{
    testGreetsEachNameInOrder(): void {
        self::assertSame(['Hello, Ada!', 'Hello, Linus!'], new Greeter()->greet(['Ada', 'Linus']));
    }
}

PHPUnit runs the compiled tests, so its configuration names .tests:

phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="default">
            <directory>.tests</directory>
        </testsuite>
    </testsuites>
</phpunit>

Requiring PHPUnit dumps the autoloader, which builds the new root:

composer require --dev phpunit/phpunit phpstan/phpstan
vendor/bin/phpunit
…
> phn build
2 files compiled, 1 written, 0 files copied, 0 stale outputs removed
…
PHPUnit 13.4.7 by Sebastian Bergmann and contributors.

Runtime:       PHP 8.5.12
Configuration: …/hello/phpunit.xml

.                                                                   1 / 1 (100%)

Time: 00:00, Memory: 20.00 MB

OK (1 test, 1 assertion)

A failing test reports a line of the compiled file, .tests/GreeterTest.php:16. phn trace rewrites such positions into the source's:

vendor/bin/phpunit | vendor/bin/phn trace
…
1) App\Tests\GreeterTest::testGreetsEachNameInOrder
Failed asserting that two arrays are identical.
…
…/hello/tests/GreeterTest.phn:9

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

The pipe's status is phn trace's, which succeeds: in a script, set pipefail so that the failing tests fail the step.

PHPStan

PHPStan analyses the outputs too:

phpstan.neon
parameters:
    level: max
    paths:
        - .src
        - .tests
vendor/bin/phpstan analyse
Note: Using configuration file …/hello/phpstan.neon.

 [OK] No errors

phn check reports what PHPStan reports at level max and may be stricter, so code that checks clean passes PHPStan on its output. The generics, lists and maps you write as types arrive as the docblocks PHPStan reads.

A .phn beside a .php

A root may hold plain PHP files too. phn build copies every file that is not a .phn into the output as it is, so a project can move to Phaenon one file at a time. Put an ordinary class in src/Punctuation.php:

src/Punctuation.php
<?php

declare(strict_types=1);

namespace App;

final class Punctuation
{
    public static function exclaim(string $text): string
    {
        return $text . '!';
    }
}

and call it from the .phn:

return array_map(fn (string $name): string => Punctuation::exclaim("{$this->greeting}, {$name}"), $names);
vendor/bin/phn check
vendor/bin/phn build
3 files checked: 0 errors, 0 warnings
2 files compiled, 1 written, 1 files copied, 0 stale outputs removed

The checker reads both languages and holds the .php file to the same rules. A finding in it fails phn check but not phn build, which copies the file as it is: a build withholds only the output of a .phn that has errors. "exclude" in phaenon.json leaves files out of the check, which helps while older code is brought up to standard. Migrate a PHP project converts the .php files when you are ready.

In production

composer install --no-dev builds the outputs as it writes the autoloader, which is why the plugin is in require. The production tree should not hold tests/: its files need PHPUnit, which --no-dev leaves out, and the build fails on them:

> phn build
tests/GreeterTest.phn:6:33: error P2001: unknown class PHPUnit\Framework\TestCase
    6 | final class GreeterTest extends TestCase
      |                                 ^^^^^^^^
…
1 of 2 files failed to compile

A root whose directory does not exist is skipped, so a deploy that copies src/ without tests/, as most container builds do, compiles src/ alone:

> phn build
1 files compiled, 1 written, 0 files copied, 0 stale outputs removed

Next