Nix flake with Node and PHP

Brief note on a nix flake that supports Node 20 and PHP 7.4. My use case is deploying an AWS CDK project that supports a Moodle 3.11 environment. I’m not version-limited on the Node version for CDK, but I need to start with PHP 7.4 to support the Moodle package code, though I’ll be moving to PHP 8.1 soon.

Here’s the flake.nix in its entirety:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
{
description = "Example JavaScript development environment for Zero to Nix";

# Flake inputs
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs?ref=nixos-unstable";
phps.url = "github:fossar/nix-phps";
};

# Flake outputs
outputs = { self, nixpkgs, phps }:
let
# Systems supported
allSystems = [
"x86_64-linux" # 64-bit Intel/AMD Linux
"aarch64-linux" # 64-bit ARM Linux
"x86_64-darwin" # 64-bit Intel macOS
"aarch64-darwin" # 64-bit ARM macOS
];

# Helper to provide system-specific attributes
forAllSystems = f: nixpkgs.lib.genAttrs allSystems (system: f {
pkgs = import nixpkgs { inherit system; };
});
in
{
# Development environment output
devShells = forAllSystems ({ pkgs }: {
default = pkgs.mkShell {
# The Nix packages provided in the environment
packages = with pkgs; [
nodejs_20 # Node.js 18, plus npm, npx, and corepack
yarn
phps.packages.${system}.php74
phps.packages.${system}.php74.packages.composer
];

shellHook = ''
yarn
npx aws-cdk --version
php -v
'';
};
});
};
}

This flake builds on the code I demonstrated in This blog post was written with Hexo and Nix. First, to get PHP 7.4 I need to bring in the nix-phps repository. First, I add it to the list of inputs:

1
2
3
4
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs?ref=nixos-unstable";
phps.url = "github:fossar/nix-phps";
};

I also need to add it as an argument for the outputs:

1
outputs = { self, nixpkgs, phps }:

If I don’t, I’ll get an error:

1
error: function 'outputs' called with unexpected argument 'phps'

Having done that, I can add the PHP packages to the package list. I didn’t find the nix-phps docs very helpful and it took some trial and error to get it right:

1
2
phps.packages.${system}.php74
phps.packages.${system}.php74.packages.composer

This installs PHP 7.4 with default extensions and also composer. The ${system} variable ensures that the correct architecture is used. I did install Cachix as part of this process; I think the extensions were still built locally. The end result works fine:

1
2
3
4
5
6
2.92.0 (build bf62e55)
PHP 7.4.33 (cli) (built: Oct 24 2023 14:46:15) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.33, Copyright (c), by Zend Technologies
(nix:nix-shell-env)

After all the difficult experiences I’ve had with building PHP on a Mac via either phpbrew or phpenv, the relative ease of the build process (Nix learning curve aside) is welcome.