PHP SDK
The PHP SDK lets you write Dagger modules in PHP. You define plain PHP classes and methods, mark them with attributes, and the SDK turns them into Dagger objects and functions that anyone can call from the CLI, from another module, or over the API. In return, your module gets generated, fully typed PHP clients: core() for the whole Dagger API, and one client for each module it uses. The core client covers containers, directories, files, secrets, and services.
This page is a standalone guide to the PHP SDK. It assumes you already understand the platform concepts covered in the SDKs overview:
- Types explains how SDK types map to the Dagger API
- Generating code explains how generators and tooling return diffs for you to apply
A useful, reusable module provides at least one of the three first-class function types: a check, a generator, or a service. The PHP SDK supports all three. See Checks, generators, services, directives, and ignore patterns for the PHP syntax.
The PHP SDK is itself a Dagger module, dagger.io/sdk/php. Install it into your workspace once, then use Dagger's module commands to scaffold, generate, and maintain PHP modules:
# Install the PHP SDK into your workspace (once)
dagger module install dagger.io/sdk/php
# Create a PHP module
dagger module init php --name my-module
Create a module
Run these commands from inside a Git repository. That's where the new module goes.
Install the PHP SDK into your workspace, then create a new module. The SDK argument is required. This example also sets the optional module name:
dagger module install dagger.io/sdk/php
dagger module init php --name my-module
dagger module init returns a changeset, a structured diff of the files it wants to create. Dagger shows you that diff to review before it writes anything to disk.
If the repository does not have a dagger.toml yet, use dagger module install --here dagger.io/sdk/php to create it in the current directory.
Where the module is created
By default, dagger module init places the new module beside the dagger.toml
it is editing:
<dagger.toml directory>/.dagger/modules/<name>
That is the workspace root unless the config lives in a subdirectory, as it does when several projects share one repository.
Pass --path to choose a different location. The path is relative to your current directory, like any other path you type, and a leading / means the workspace root.
dagger module init php --name my-module --path ci # ./ci
dagger module init php --name my-module --path /ci # <workspace root>/ci
Dagger registers a module at a custom path as authored by the SDK but does not install it as a callable workspace module. Run dagger module install ./ci to install it too.
The PHP SDK ships two starter templates. default gives the main class a constructor over the workspace and a container function. empty gives the main class alone. Pass --template to pick one by name:
dagger module init php --name my-module --template empty
dagger.toml keeps a template other than default as a setting of the module's scope.
List the PHP SDK's module initialization options with:
dagger module init php --help
Resulting file layout
Once initialized and generated, a PHP module looks like this:
my-module/
├── dagger-module.toml # generated: name and entrypoint
├── composer.json
├── composer.lock # generated: written by generation's composer install
├── src/
│ └── MyModule.php # your code
├── sdk/ # generated: the PHP library and its clients
│ ├── generated/ # the core API, and each module client under Clients/
│ └── entrypoint/ # the Dang entrypoint the engine runs
├── vendor/ # composer dependencies (gitignored)
└── .gitignore # ignores vendor/
dagger module init updates the workspace config and runs the PHP SDK's generator for the new module. The generator writes the template's composer.json and src/MyModule.php, then dagger-module.toml, sdk/, composer.lock, and .gitignore, all in the same changeset.
Commit sdk/ and composer.lock with the rest of the module. A module runs from its committed generated files, from a local checkout as from a Git ref. .gitignore excludes only vendor/. See Regenerate bindings.
The module manifest contains the module's name and an [entrypoint] table:
name = "my-module"
[entrypoint]
kind = "dang"
source = "./sdk/entrypoint"
The entrypoint is a generated Dang module that Dagger runs and that calls your PHP code in the module's container. The workspace's dagger.toml records the SDK under sdks.php and records the module path as one of its scopes. That scope is how the PHP SDK's generator finds workspace modules.
composer.json declares the module as a Composer package in the DaggerModule namespace. It depends on the SDK library, dagger/dagger, through a path repository to ./sdk:
{
"name": "daggermodule/my-module",
"description": "",
"version": "1.0.0",
"minimum-stability": "dev",
"license": "proprietary",
"authors": [
],
"repositories": [
{
"type": "path",
"url": "./sdk"
}
],
"require": {
"php": "^8.2",
"dagger/dagger": "*@dev"
},
"autoload": {
"psr-4": {
"DaggerModule\\": "src/"
}
},
"config": {
"platform": {
"php": "8.3.7"
}
}
}
Define objects and functions
A PHP module is a set of classes in the DaggerModule namespace under src/. The main object is a class whose name matches your module, PascalCased. A module named my-module has a MyModule class in src/MyModule.php. Mark classes with #[DaggerObject], and every public method marked with #[DaggerFunction] becomes a callable Dagger Function.
<?php
declare(strict_types=1);
namespace DaggerModule;
use Dagger\Attribute\DaggerFunction;
use Dagger\Attribute\DaggerObject;
use Dagger\Attribute\Doc;
#[DaggerObject]
#[Doc('A simple example module to say hello.')]
class MyModule
{
#[DaggerFunction]
#[Doc('Return a greeting')]
public function hello(
#[Doc('Who to greet')]
string $name,
#[Doc('The greeting to display')]
string $greeting,
): string {
return "{$greeting}, {$name}!";
}
#[DaggerFunction]
#[Doc('Return a loud greeting')]
public function loudHello(
#[Doc('Who to greet')]
string $name,
#[Doc('The greeting to display')]
string $greeting,
): string {
return strtoupper("{$greeting}, {$name}!");
}
}
Key rules:
- Classes live in the
DaggerModulenamespace undersrc/; the SDK scans that directory for classes with the#[DaggerObject]attribute. - Each class lives in its own file, named after the class, as Composer's PSR-4 autoloading expects. A call that reaches a class declared in another class's file fails with
No class DaggerModule\Account exists. - Run
dagger generateafter adding a function or changing a signature. Dagger reads a module's functions from its generated entrypoint, so a new function is an unknown command until then. - A method becomes a Dagger Function only when it is
publicand has the#[DaggerFunction]attribute. Private methods, and public methods without the attribute, are ordinary PHP helpers, invisible to callers. - Every parameter and return type needs a type hint. The SDK supports named types and nullable named types (
?string). It does not support union or intersection types. - Throw an exception to fail a function. The caller sees the message.
dagger module init --name my-module installs the module in the workspace as my-module. Call an installed module's functions by that name. The workspace main module is called without a name, and -m <path> loads a module by path:
dagger api call my-module hello --name=World --greeting=Hello
# Hello, World!
dagger api call my-module loud-hello --name=World --greeting=Hello
# HELLO, WORLD!
The CLI converts PHP method and argument names to kebab-case (loudHello becomes loud-hello, $name becomes --name).
The constructor
Mark __construct on the main class with #[DaggerFunction] to make it the module's constructor. Its arguments become arguments of the main object, and the initialized instance is the main object. Use it for module-wide configuration and shared state.
A common pattern is to accept a Workspace so the module can read the project it runs against (see Workspace inputs). Dagger fills it in from the current workspace and pulls content lazily, so you store the project directory once and reuse it:
<?php
declare(strict_types=1);
namespace DaggerModule;
use Dagger\Attribute\DaggerFunction;
use Dagger\Attribute\DaggerObject;
use Dagger\Attribute\Doc;
use Dagger\Attribute\ReturnsListOfType;
use Dagger\Directory;
use Dagger\Workspace;
use function Dagger\core;
#[DaggerObject]
class MyModule
{
private Directory $source;
#[DaggerFunction]
public function __construct(
#[Doc('The current workspace, auto-populated by Dagger.')]
Workspace $ws,
) {
// Read the workspace root; nothing is uploaded until a function uses it.
$this->source = $ws->directory('/');
}
#[DaggerFunction]
#[ReturnsListOfType('string')]
public function foo(): array
{
return core()
->container()
->from('alpine:latest')
->withMountedDirectory('/app', $this->source)
->directory('/app')
->entries();
}
}
Every property on the object, public or private, is part of its state, and Dagger serializes it between functions in a chain. Only public properties marked with #[DaggerFunction] show up in the API as readable fields. Everything else stays private to Dagger:
#[DaggerObject]
class LintRun
{
#[DaggerFunction]
#[Doc('The directory that was linted')]
public Directory $source;
// Present in PHP, hidden from the API.
private string $report = '';
}
Constructor promotion works too, so public function __construct(private readonly string $greeting = 'Hello') both declares the argument and stores it. A class that declares fields but no constructor gets an implicit argument-less constructor.
Arguments and return values
Dagger derives a function's argument and return types from the PHP signature. The mapping is:
| PHP type | Dagger type |
|---|---|
string | String |
int | Int |
float | Float |
bool | Boolean |
void or null | Void |
array with #[ListOfType('T')] / #[ReturnsListOfType('T')] | [T] (list) |
Dagger\Directory | Directory |
Dagger\File | File |
Dagger\Container | Container |
Dagger\Secret | Secret |
Dagger\Service | Service |
a #[DaggerObject] class T | object T |
a #[DaggerObject] enum T | enum T |
Lists
PHP's array type carries no element type, so a list argument or return value must declare its element type with an attribute. Use #[ListOfType] on parameters and fields, and #[ReturnsListOfType] on methods. The SDK does not read docblock annotations such as @param string[].
use Dagger\Attribute\ListOfType;
use Dagger\Attribute\ReturnsListOfType;
use Dagger\Directory;
#[DaggerFunction]
#[ReturnsListOfType('string')]
public function capitalizeStrings(
#[ListOfType('string')]
array $values,
): array {
return array_map(fn(string $v) => ucwords($v), $values);
}
#[DaggerFunction]
#[ReturnsListOfType(Directory::class)]
public function split(
#[ListOfType(Directory::class)]
array $dirs,
): array {
return $dirs;
}
The element type may be a scalar name ('string', 'int', 'float', 'bool'), a class name, or a nested ListOfType for lists of lists.
Documentation
The #[Doc] attribute becomes API documentation, shown by dagger api functions and dagger api call --help. Place it on a method to document the function, on a parameter to document that argument, and on the main class to document the whole module. The SDK ignores PHP docblocks.
#[DaggerFunction]
#[Doc('Return a greeting')]
public function hello(
#[Doc('Who to greet')]
string $name,
): string {
return "Hello, {$name}!";
}
Optional and default arguments
Dagger arguments are required by default. Make one optional with a PHP default value or a nullable type:
#[DaggerFunction]
public function hello(string $name = 'world'): string
{
return "Hello, {$name}";
}
#[DaggerFunction]
public function hello(?string $name): string
{
if ($name !== null) {
return "Hello, {$name}";
}
return 'Hello, world';
}
- A PHP default value (
string $name = 'world') makes the argument optional and supplies the default when the caller omits it. - A nullable type with no default (
?string $name) makes the argument optional and passesnullwhen omitted, so you can detect "not passed." - A
DirectoryorFileparameter with#[DefaultPath]is also optional; see Default paths.
Nullability
Use a nullable type (?Dagger\Secret, ?Dagger\Container) when an argument may be absent. null means the caller passed null or nothing at all. Non-nullable scalars are always present. A common constructor pattern falls back to a computed default:
#[DaggerFunction]
public function __construct(?Container $ctr = null)
{
$this->ctr = $ctr ?? core()->container()->from('alpine:3');
}
Enums
Model a closed set of values as a PHP enum marked with #[DaggerObject]. Dagger turns it into an enum and validates inputs. #[Doc] works on the enum itself and on each case:
<?php
declare(strict_types=1);
namespace DaggerModule;
use Dagger\Attribute\DaggerObject;
use Dagger\Attribute\Doc;
#[DaggerObject]
#[Doc('Vulnerability severity levels.')]
enum Severity: string
{
#[Doc('Undetermined risk; analyze further.')]
case Unknown = 'UNKNOWN';
#[Doc('Minimal risk; routine fix.')]
case Low = 'LOW';
#[Doc('Moderate risk; timely fix.')]
case Medium = 'MEDIUM';
#[Doc('Serious risk; quick fix needed.')]
case High = 'HIGH';
#[Doc('Severe risk; immediate action.')]
case Critical = 'CRITICAL';
}
Type a parameter with the enum and Dagger hands you the matching case; return one and the caller sees its API identifier:
#[DaggerFunction]
public function scan(string $ref, Severity $severity): string
{
return core()
->container()
->from('aquasec/trivy:0.50.4')
->withExec(['trivy', 'image', "--severity={$severity->value}", $ref])
->stdout();
}
The #[DaggerObject] attribute is required on the enum. Without it the enum is never discovered, and the module fails to load with an error like find mod type for function "scan" arg "severity" type: "MyModuleSeverity!", which makes every function uncallable, not just the one referencing the enum.
The API identifier for each choice comes from the PHP case name, upper-snake-cased (Critical becomes CRITICAL, NotFound becomes NOT_FOUND), never from the backing value. The backing value stays yours to use inside PHP, through $severity->value. Keeping the two aligned, as above, avoids surprises.
Matching is case-insensitive, so --severity=critical and --severity=CRITICAL both work. The backing value is not accepted: only the API identifier is.
Passing a value outside the enum produces a clear error listing the allowed choices:
dagger api call scan --ref=alpine:latest --severity=FOO
# invalid argument "FOO" for "--severity" flag: value should be one of CRITICAL,HIGH,LOW,MEDIUM,UNKNOWN
Any PHP enum works. The backing type is your business: the API identifier always comes from the case name, so a pure enum (enum Severity { case Low; }) and an int-backed one (enum Severity: int) register exactly like the string-backed one above. Only an enum with no cases at all is rejected.
The naming rule above applies to the enums your module declares. The generated client also includes enums that already exist in the Dagger API (for example Dagger\NetworkProtocol) as PHP enums, with case names taken straight from the API; pass them to core API calls and use them in your own signatures as usual.
Custom object types
Return an instance of another #[DaggerObject] class to expose a custom object. Public properties marked #[DaggerFunction] become readable fields, and #[DaggerFunction] methods on the class become chainable functions. Dagger prefixes custom type names with the module name in the API schema (for example MyModuleOrganization) to avoid collisions:
<?php
declare(strict_types=1);
namespace DaggerModule;
use Dagger\Attribute\DaggerFunction;
use Dagger\Attribute\DaggerObject;
#[DaggerObject]
class MyModule
{
#[DaggerFunction]
public function daggerOrganization(): Organization
{
return new Organization(
url: 'https://github.com/dagger',
members: [
new Account('jane', 'jane@example.com'),
new Account('john', 'john@example.com'),
],
);
}
}
<?php
declare(strict_types=1);
namespace DaggerModule;
use Dagger\Attribute\DaggerFunction;
use Dagger\Attribute\DaggerObject;
use Dagger\Attribute\ListOfType;
#[DaggerObject]
class Organization
{
public function __construct(
#[DaggerFunction]
public string $url,
#[DaggerFunction]
#[ListOfType(Account::class)]
public array $members,
) {
}
}
<?php
declare(strict_types=1);
namespace DaggerModule;
use Dagger\Attribute\DaggerFunction;
use Dagger\Attribute\DaggerObject;
#[DaggerObject]
class Account
{
public function __construct(
#[DaggerFunction]
public string $username,
#[DaggerFunction]
public string $email,
) {
}
#[DaggerFunction]
public function url(): string
{
return 'https://github.com/' . $this->username;
}
}
The SDK discovers every #[DaggerObject] class under src/. You can then chain calls on the CLI and API:
dagger api call my-module dagger-organization members url
https://github.com/jane
https://github.com/john
Interfaces
An interface lets a function accept any object that provides the functions it needs, whatever module it comes from. A PHP interface with #[DaggerObject] declares one. Each of its methods needs #[DaggerFunction]:
<?php
declare(strict_types=1);
namespace DaggerModule;
use Dagger\Attribute\DaggerFunction;
use Dagger\Attribute\DaggerObject;
use Dagger\Attribute\Doc;
use Dagger\Directory;
#[DaggerObject]
#[Doc('Anything that lints a directory')]
interface Linter
{
#[DaggerFunction]
#[Doc('The linter\'s report for a directory')]
public function lintReport(Directory $source): string;
}
#[DaggerFunction]
#[Doc('Lint the project with any linter')]
public function lintWith(
#[Doc('The linter to run')]
Linter $linter,
): string {
return $linter->lintReport($this->source);
}
Any object with a matching lintReport function satisfies Linter. This phpcs module, created with --template empty, provides one:
<?php
declare(strict_types=1);
namespace DaggerModule;
use Dagger\Attribute\DaggerFunction;
use Dagger\Attribute\DaggerObject;
use Dagger\Attribute\Doc;
use Dagger\Directory;
use Dagger\ReturnType;
use function Dagger\core;
#[DaggerObject]
#[Doc('Lint PHP code with PHP_CodeSniffer.')]
class Phpcs
{
#[DaggerFunction]
#[Doc('PHP_CodeSniffer\'s report for a directory')]
public function lintReport(
#[Doc('The PHP code to lint')]
Directory $source,
): string {
return core()
->container()
->from('composer:2')
->withExec(['composer', 'global', 'require', '--quiet', 'squizlabs/php_codesniffer'])
->withDirectory('/src', $source)
->withWorkdir('/src')
->withExec(['/tmp/vendor/bin/phpcs', '--standard=PSR12', '--report=summary', 'app'], expect: ReturnType::ANY)
->stdout();
}
}
Pass the phpcs module where my-module expects a Linter:
dagger -c 'my-module | lint-with $(phpcs)'
PHP CODE SNIFFER REPORT SUMMARY
...
/src/app/src/legacy.php 5 0
...
A TOTAL OF 5 ERRORS AND 0 WARNINGS WERE FOUND IN 1 FILE
...
A function can also take a list of an interface, and return an interface, or a list of one, that it received as an argument. Interfaces have these limits:
- A method of an interface takes and returns only
bool,int,float,string,void, and non-null core objects such asDirectory. - An object field cannot hold an interface.
- A module loaded under another name, as a dependency alias, cannot take its own interfaces.
Working with core Dagger types
The generated client exposes the whole Dagger API through the core() function, imported with use function Dagger\core;. You use it to build containers, mount directories and files, handle secrets, and run services. Core types live in the Dagger namespace (Dagger\Container, Dagger\Directory, and so on).
Containers
Each builder method returns a new, immutable Container. Nothing mutates in place, and Dagger content-addresses and caches every step for you.
use Dagger\Container;
use Dagger\Directory;
#[DaggerFunction]
#[Doc('Build and return a container')]
public function build(Directory $source): Container
{
return core()
->container()
->from('node:20')
->withDirectory('/app', $source)
->withWorkdir('/app')
->withExec(['npm', 'install'])
->withExec(['npm', 'run', 'build']);
}
Directories and files
Directory and File are first-class, "just-in-time" artifacts. You can accept them as arguments, return them, mount them into containers, and export them to the host. Less common parameters are optional PHP arguments, so pass them by name. For example, withDirectory accepts exclude:
#[DaggerFunction]
public function copyDirectoryWithExclusions(
#[Doc('Source directory')]
Directory $source,
#[Doc('Exclusion patterns')]
#[ListOfType('string')]
array $exclude = [],
): Container {
return core()
->container()
->from('alpine:latest')
->withDirectory('/src', $source, exclude: $exclude);
}
The same pattern holds across the whole client. Required parameters are positional, and optional ones are named arguments with defaults.
Workspace inputs
When a module needs to read the user's project, whether the source tree, config files, or lockfiles, it takes a Dagger\Workspace argument, almost always on the constructor. You don't pass it. Dagger fills it in from the current workspace and uploads nothing up front. Dagger pulls project content only when a function actually reads a path, so a module can declare access to the whole workspace cheaply and pay only for what it touches.
<?php
declare(strict_types=1);
namespace DaggerModule;
use Dagger\Attribute\DaggerFunction;
use Dagger\Attribute\DaggerObject;
use Dagger\Attribute\Doc;
use Dagger\Container;
use Dagger\Directory;
use Dagger\Workspace;
use function Dagger\core;
#[DaggerObject]
class MyModule
{
private Directory $source;
#[DaggerFunction]
public function __construct(
#[Doc('The current workspace, auto-populated by Dagger.')]
Workspace $ws,
) {
// Pull the workspace root as a Directory (lazy, no upload yet).
$this->source = $ws->directory('/');
}
// Functions reuse the pulled Directory like any other.
#[DaggerFunction]
public function build(): Container
{
return core()
->container()
->from('node:20')
->withDirectory('/app', $this->source)
->withWorkdir('/app')
->withExec(['npm', 'install'])
->withExec(['npm', 'run', 'build']);
}
}
The Workspace client type exposes accessors for reading project content:
| Accessor | Signature | Returns |
|---|---|---|
directory | $ws->directory(string $path, ?array $exclude = [], ?array $include = [], ?bool $gitignore = false): Directory | a Directory at $path |
file | $ws->file(string $path): File | a File at $path |
findUp | $ws->findUp(string $name, ?string $from = '.'): string | the workspace path of $name, searching upward |
Path resolution. A relative path resolves from the workspace's current working directory. An absolute path (starting with /) resolves from the workspace root, also called the boundary. So $ws->directory('/') is the whole project root, while $ws->directory('.') is wherever the user invoked Dagger from.
Excluding files. directory takes named exclude, include, and gitignore arguments to filter what gets pulled. Tight filters matter for caching. Every file you load is a file whose change can invalidate the cache, so load only what the build needs:
#[DaggerFunction]
public function __construct(Workspace $ws)
{
$this->source = $ws->directory(
'/',
exclude: ['vendor', '.git', 'dist'],
// include: ['app/', 'composer.*'], // allowlist instead
// gitignore: true, // apply .gitignore rules
);
}
findUp walks up from a start path and returns the absolute workspace path of the first match, stopping at the workspace boundary. Relative start paths resolve from the workspace cwd; pass from: to change it. Use it to find a project root marker such as composer.json.
To use the current workspace, declare a Dagger\Workspace argument on the module constructor or function. Dagger injects it automatically and omits it from the CLI arguments.
Default paths
When someone calls a function from a module directory rather than a workspace, a Directory or File argument can default to a path in the caller's project with the #[DefaultPath] attribute. The argument becomes optional. When the caller omits it, Dagger loads the path from the caller's context (the Git repository root for absolute paths, the module directory for relative ones):
use Dagger\Attribute\DefaultPath;
use Dagger\Attribute\Ignore;
#[DaggerFunction]
#[ReturnsListOfType('string')]
public function readDir(
#[DefaultPath('.')]
#[Ignore('vendor/', 'tests/')]
Directory $source,
): array {
return $source->entries();
}
#[Ignore] filters what gets loaded for a Directory argument, using .gitignore syntax. Prefer the Workspace pattern above for new modules. Default paths are still useful for functions that must work when no workspace is present.
Secrets
Accept sensitive values as Dagger\Secret, never as plain strings. Dagger scrubs secret plaintext from logs, caches, and crash reports:
use Dagger\Secret;
#[DaggerFunction]
#[Doc('Query the GitHub API')]
public function githubApi(
#[Doc('GitHub API token')]
Secret $token,
): string {
return core()
->container()
->from('alpine:3.17')
->withSecretVariable('GITHUB_API_TOKEN', $token)
->withExec(['apk', 'add', 'curl'])
->withExec(['sh', '-c', 'curl "https://api.github.com/repos/dagger/dagger/issues" --header "Authorization: Bearer $GITHUB_API_TOKEN"'])
->stdout();
}
Callers supply secrets through providers on the CLI:
dagger api call my-module github-api --token=env://GITHUB_TOKEN # environment variable
dagger api call my-module github-api --token=file://./token.txt # file
dagger api call my-module github-api --token="cmd://gh auth token" # command output
dagger api call my-module github-api --token=op://vault/item/field # 1Password
Services
Return Dagger\Service to expose a long-running service, and bind it into other containers with withServiceBinding. Services are content-addressed, so a given definition always gets the same hostname and port conflicts never come up:
use Dagger\Service;
#[DaggerFunction]
#[Doc('Start and return an HTTP service')]
public function httpService(): Service
{
return core()
->container()
->from('python')
->withWorkdir('/srv')
->withNewFile('index.html', 'Hello, world!')
->withExposedPort(8080)
->asService(args: ['python', '-m', 'http.server', '8080']);
}
#[DaggerFunction]
#[Doc('Send a request to an HTTP service and return the response')]
public function get(): string
{
return core()
->container()
->from('alpine')
->withServiceBinding('www', $this->httpService())
->withExec(['wget', '-O-', 'http://www:8080'])
->stdout();
}
A larger example
Real modules combine these pieces. This module reads the workspace once in its constructor, caches Composer downloads in a cache volume, exposes a build function, and turns a test run into a check:
<?php
declare(strict_types=1);
namespace DaggerModule;
use Dagger\Attribute\Check;
use Dagger\Attribute\DaggerFunction;
use Dagger\Attribute\DaggerObject;
use Dagger\Attribute\Doc;
use Dagger\Container;
use Dagger\Directory;
use Dagger\Workspace;
use function Dagger\core;
#[DaggerObject]
#[Doc('Build and test a PHP application')]
class MyModule
{
private Directory $source;
#[DaggerFunction]
public function __construct(Workspace $ws)
{
$this->source = $ws->directory('/', exclude: ['vendor', '.git']);
}
#[DaggerFunction]
#[Doc('Return a container with the application and its dependencies installed')]
public function build(): Container
{
return core()
->container()
->from('composer:2')
->withMountedCache('/tmp/cache', core()->cacheVolume('composer'))
->withDirectory('/app', $this->source)
->withWorkdir('/app')
->withExec(['composer', 'install', '--no-interaction']);
}
#[DaggerFunction, Check]
#[Doc('Run the test suite')]
public function test(): void
{
$this->build()->withExec(['vendor/bin/phpunit'])->sync();
}
#[DaggerFunction]
#[Doc('Return the number of failing tests, parsed from the report')]
public function failures(): int
{
$report = $this->build()
->withExec(['vendor/bin/phpunit', '--log-junit', 'report.xml'], expect: \Dagger\ReturnType::ANY)
->file('report.xml')
->contents();
$xml = new \SimpleXMLElement($report);
return (int) $xml->testsuite['failures'];
}
}
Module dependencies
A module calls another module through a generated client. Manage clients from the module directory:
cd .dagger/modules/my-module
dagger module client add ../phpcs
dagger module client list
dagger module client list shows each client's exact target. Pass that target to dagger module client rm to remove the client:
SCOPE SDK TARGET
.dagger/modules/my-module php ./.dagger/modules/phpcs
Client add and remove commands update the scope's clients in dagger.toml, and run generation. No client reaches the module manifest:
[sdks.php.scopes.".dagger/modules/my-module"]
is-module = true
name = "my-module"
clients = ["./.dagger/modules/phpcs"]
Generation writes the client to sdk/generated/Clients/Phpcs/, in the namespace Dagger\Clients\Phpcs, named after the module in PascalCase. sdk/composer.json already autoloads it, so the module's composer.json does not change. A call starts from a static method of the client's Client class, named after the module:
use Dagger\Clients\Phpcs\Client as Phpcs;
#[DaggerFunction]
#[Doc('Lint the project with PHP_CodeSniffer')]
public function phpcsReport(): string
{
return Phpcs::phpcs()->lintReport($this->source);
}
dagger api call my-module phpcs-report prints the same report as lint-with above.
A client shares the session of core(), so core objects such as a Directory pass into its calls. A module function cannot take or return a client's type. See Client libraries for client commands and targets.
Use Composer for ordinary PHP packages (composer require), and Dagger clients for Dagger modules. Installing a Dagger module through Composer does not register it with Dagger, so you cannot call it.
The global client
Code written for the built-in PHP runtime calls the global client, Dagger\dag(). A new module does not get it. A module moved from the built-in runtime keeps it, as does a module whose sdk/ already has it. Pass --global-client to dagger module init, or set globalClient in the scope's settings, to decide:
[sdks.php.scopes.".dagger/modules/my-module".settings]
globalClient = true
With true, generation writes sdk/src/dag.php, which defines dag(). With false, it leaves the file out. dag() returns the same client as core(), so it restores core calls only. Call a module through its client. The global client is temporary: move the code to core() and set globalClient = false.
Regenerate bindings and generated files
A PHP module uses generated code alongside your handwritten src/:
sdk/is the SDK library with its clients and entrypoint.sdk/generated/holds the core API (Container,Directory, and the rest) and each module client.sdk/entrypoint/holds the Dang module the engine runs to register and call your functionscomposer.lockis the resolved Composer dependencies, including the SDK library
Don't edit sdk/ by hand. Commit sdk/ and composer.lock with the module. The generated .gitignore excludes only local installs, and sdk/.gitattributes marks the generated files:
/vendor/
** linguist-generated
Regenerate after a change to what the module declares (a function, an argument, an attribute) or to its clients. Use dagger generate, which returns a changeset:
# Review the regenerated files, then apply
dagger generate
dagger generate discovers and runs every generator in the workspace. For modules registered under the PHP SDK, that includes php-sdk:generate, which regenerates sdk/ and composer.lock.
An edit to a function's body runs at once. A call builds the module's container from its current source. The build installs the Composer dependencies before it copies src/, so an edit to src/ reuses the installed packages.
A .dagger-php-sdk-skip-generate marker in a module or one of its ancestors skips PHP binding regeneration for that module.
Engine version
A PHP module's manifest has no engineVersion, and generation removes one. The Dagger API version a module uses is recorded in sdk/entrypoint/dang.toml:
dang = "2.1"
[imports]
[imports.Dagger]
dagger = "v1.0.0-beta.27"
This version is the SDK's target engine version. The SDK release sets it, and the module gets a new one at its next dagger generate after an SDK update. Generation also pins each client's schema to this version, not to the engine version the client module requires. The SDK needs an engine v1.0.0-beta.27 or newer. On an older engine, dagger module init and dagger generate stop with a message that names the engine.
Checks, generators, services, directives, and ignore patterns
A useful, reusable module provides at least one of the three first-class function types: a check, a generator, or a service. That gives the platform verbs (dagger check, dagger generate, dagger start) something to run. See the SDKs overview for the full treatment.
In PHP, you mark each function type with an attribute next to #[DaggerFunction]. Agents work the same way, for dagger agent:
| Attribute | Return type | Run by | Purpose |
|---|---|---|---|
#[Check] | void | dagger check | validate the project (test/lint/scan) |
#[Generate] | Changeset | dagger generate | produce a diff to apply to the workspace |
#[Up] | Service | dagger start | start a long-running service |
#[Agent] | LLM | dagger agent | give an LLM a task |
A check, a generator, or a service takes no required arguments other than a Workspace. An agent takes exactly one required LLM. dagger generate refuses a function that does not match its row, and names it:
Dagger\Exception\RegistrationError\Invalid: 'needsArg' is labeled as a check, but requires 'name'.
Attributes
PHP modules use attributes from the Dagger\Attribute namespace to add Dagger metadata that PHP's type system can't express:
| Attribute | Placement | Meaning |
|---|---|---|
#[DaggerObject] | class, enum, or interface | expose the class as a Dagger object, the enum as a Dagger enum, or the interface as a Dagger interface |
#[DaggerFunction] | public method or property | expose the method as a function, or the property as a field |
#[Doc('...')] | class, enum, enum case, method, or parameter | API documentation |
#[Check] | method (with #[DaggerFunction]) | mark the function as a check |
#[Generate] | method (with #[DaggerFunction]) | mark the function as a generator |
#[Up] | method (with #[DaggerFunction]) | mark the function as a service |
#[Agent] | method (with #[DaggerFunction]) | mark the function as an agent |
#[ListOfType('T')] | array parameter or property | element type of a list |
#[ReturnsListOfType('T')] | method returning array | element type of the returned list |
#[DefaultPath('...')] | Directory or File parameter | default the argument to a path in the caller's project |
#[Ignore('...', ...)] | Directory parameter | exclude paths when loading the argument |
Attributes can be combined on one line: #[DaggerFunction, Check].
No PHP attribute sets a cache policy, so every function gets the engine's default.
Ignore patterns
A module reads the user's project through a Workspace argument (see Workspace inputs), not a path-defaulted Directory. To filter what gets pulled, use the exclude argument when reading a workspace directory. Tight filters matter for caching, since loading less means fewer cache invalidations:
#[DaggerFunction]
public function __construct(Workspace $ws)
{
$this->source = $ws->directory('/', exclude: ['vendor', '.git', 'dist']);
}
For Directory arguments that callers pass explicitly (or that use #[DefaultPath]), the #[Ignore] attribute applies the same filtering with .gitignore syntax; see Default paths.
Checks
Add the #[Check] attribute next to #[DaggerFunction] to make a function a check, a validation function (test, lint, scan) that takes no required arguments other than a Workspace. dagger check discovers and runs every check a module exposes. A check must return void. The engine refuses to load a module whose check returns anything else, such as a Container. A check fails when it throws an exception. To run a container as a check, call sync() on it: a non-zero exit throws, which fails the check.
use Dagger\Attribute\Check;
#[DaggerFunction, Check]
#[Doc('Lint the project')]
public function lint(): void
{
$output = core()
->container()
->from('php:8.4-cli-alpine')
->withMountedDirectory('/src', $this->source)
->withWorkdir('/src')
->withExec(['sh', '-c', 'find . -name "*.php" -not -path "./vendor/*" -exec php -l {} \;'])
->stdout();
if (str_contains($output, 'Parse error')) {
throw new \RuntimeException($output);
}
}
// sync() runs the container; a non-zero exit fails the check.
#[DaggerFunction, Check]
#[Doc('Run the test suite')]
public function test(): void
{
$this->build()->withExec(['vendor/bin/phpunit'])->sync();
}
You can also declare checks on custom object types to group them, for example a Test object with lint and unit checks. List the checks with dagger check -l:
dagger check -l
MODULE CHECK DESCRIPTION
my-module lint Lint the project
my-module stale staleness check: lock the project's Composer dependencies
my-module test Run the test suite
php-sdk stale staleness check: re-generate modules and clients managed by the PHP SDK
Each generator adds a stale check, which fails when dagger generate would change files. Run a subset by name pattern with dagger check 'dag://my-module/test*'.
Generators
Add the #[Generate] attribute next to #[DaggerFunction] to make a function a generator. It runs a tool, captures the resulting directory, diffs that against the source, and returns the result as a Changeset. Directory::changes computes it:
use Dagger\Attribute\Generate;
use Dagger\Changeset;
#[DaggerFunction, Generate]
#[Doc('Lock the project\'s Composer dependencies')]
public function lockfile(): Changeset
{
$locked = core()
->container()
->from('composer:2')
->withDirectory('/app', $this->source)
->withWorkdir('/app')
->withExec(['composer', 'update', '--no-install', '--no-interaction'])
->directory('/app');
return $locked->changes($this->source);
}
dagger generate runs every generator in the workspace, including the SDK's own php-sdk:generate, and presents the combined changeset for you to review and apply. List the generators with -l:
dagger generate -l
MODULE GENERATOR DESCRIPTION
my-module lockfile Lock the project's Composer dependencies
php-sdk generate re-generate modules and clients managed by the PHP SDK
Run one by name. The changeset of my-module:lockfile adds composer.lock at the workspace root:
dagger generate my-module:lockfile
Services
A function that returns a Service and takes no required arguments is a service. dagger start discovers and starts every service the module exposes and opens their ports on the host. Add the #[Up] attribute to mark a service explicitly, so that the SDK checks its signature:
use Dagger\Attribute\Up;
use Dagger\Service;
#[DaggerFunction, Up]
#[Doc('Serve the application on port 8080')]
public function serve(): Service
{
return $this->build()
->withExposedPort(8080)
->asService(args: ['php', '-S', '0.0.0.0:8080', '-t', 'app']);
}
dagger start -l lists it with the httpService function from Services, which has no attribute:
dagger start -l
MODULE SERVICE DESCRIPTION
my-module http-service Start and return an HTTP service
my-module serve Serve the application on port 8080
Agents
Add #[Agent] to make a function an agent, such as review(LLM $base): LLM. The function takes an LLM. It gives the LLM inputs and a prompt, and returns it. dagger agent composes the workspace's agents into an interactive prompt. It needs an LLM provider. dagger agent -l lists the agents:
MODULE EXPERTISE DESCRIPTION
my-module review Review the project's PHP code
Testing PHP modules
Because a PHP module is an ordinary Composer package, you can test it two ways. Unit tests are fast and need no engine. Checks need an engine, but they test the thing you actually ship.
Idiomatic PHP tests
You can unit-test functions that contain pure PHP logic, such as parsing a report or formatting a summary, with PHPUnit and no engine involved. Add it as a development dependency and put tests in a tests/ directory:
composer require --dev phpunit/phpunit
<?php
declare(strict_types=1);
namespace DaggerModule\Tests;
use DaggerModule\Issue;
use PHPUnit\Framework\TestCase;
final class IssueTest extends TestCase
{
public function testSummary(): void
{
$issue = new Issue(
filename: '/src/app/main.php',
message: 'undefined variable',
row: 12,
);
$this->assertSame('app/main.php:12 error: undefined variable', $issue->summary());
}
}
Run them like any PHPUnit suite. They don't need the engine, but they do need the generated client installed locally (see IDE and Composer setup):
vendor/bin/phpunit tests
Functional tests via checks
For behavior that exercises containers and the Dagger API, write functions in your module and call them, or make them checks so they run under dagger check. A check that builds, lints, or tests your project is both a CI gate and a smoke test:
# Smoke test: does it build?
dagger api call my-module build
# Run all checks
dagger check
# Run generators and confirm there's no drift
dagger check --generated=true
In CI
Run dagger check in CI to run every check the module exposes. The heavy lifting happens in content-addressed containers, so the same command behaves the same on a laptop and on a CI runner, with full caching:
jobs:
ci:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dagger/dagger-for-github@v6
with:
verb: check
IDE and Composer setup
The module's composer.json resolves the dagger/dagger client from the local ./sdk path repository. A fresh checkout has the committed client in sdk/ but no vendor/, so your editor cannot resolve Dagger\Container or core() until Composer installs it. To get autocompletion and go-to-definition:
# Install the generated client, and any other dependencies, into ./vendor
composer install
Repeat dagger generate after adding a client so the local sdk/ includes it.
Local development needs PHP 8.2 or newer and Composer. The runtime container uses PHP 8.4, so anything that runs locally on a recent PHP also runs in the engine.
Third-party packages are ordinary Composer dependencies. Add them with composer require; the module's build runs composer install when it loads the module, so they are available inside your functions. Keep composer.json and composer.lock in version control.
Do not publish Dagger modules to Packagist. Consumers install modules through Dagger (dagger module install), not Composer. Dagger does not register a module pulled in as a Composer package, so you cannot call its functions.
Packaging and release
You distribute a PHP SDK module as a Git repository. There is no build artifact to publish. Consumers fetch the source by reference. Dagger runs the module from its committed sdk/, and the build installs Composer dependencies when it loads the module.
Recommended release checklist:
- Commit the generated files. Run
dagger generate, review the changes, and commitcomposer.json,composer.lock, andsdk/with your module.vendor/stays gitignored. - Version with Git tags. Tag a release (for example,
v1.2.0) and push it. Consumers can pin that version with@v1.2.0.
Before publishing, run dagger check --generated=true to confirm that the committed files are up to date.
Consumers can install your module into a workspace with:
dagger module install github.com/you/your-module@v1.2.0
To call it from another module, add it as a client with dagger module client add from that module's directory. See Module dependencies.
A module reference follows [proto://]host/repo[/subpath][@version]. The version may be a tag, branch, or commit, and Dagger resolves it over HTTPS or SSH depending on the authentication available.
Migrate from the built-in PHP runtime
A module written for the engine's built-in PHP runtime moves to the generated entrypoint at its next dagger generate. Convert a legacy dagger.json first. From the workspace root:
dagger module migrate ci
dagger generate
dagger module migrate records the module's dependencies as clients of its scope, and dagger generate generates them. Generation does not change the module's code, so update each call to a dependency:
// On the built-in runtime:
$report = dag()->phpcs()->lintReport($source);
// On the generated entrypoint:
use Dagger\Clients\Phpcs\Client as Phpcs;
$report = Phpcs::phpcs()->lintReport($source);
Generation refuses a module that cannot move, and changes nothing. The refusal names the reason, and the PHP SDK README gives its fix:
module at ci2 is on the PHP runtime, which this SDK no longer generates, and cannot move to the generated entrypoint: its source is module. See "Migrate from the built-in PHP runtime" in the php-sdk README
Troubleshooting
dagger init / dagger develop not found. Install the PHP SDK with dagger module install dagger.io/sdk/php, scaffold with dagger module init php --name <name>, and regenerate with dagger generate.
Nothing was written after dagger module init. The command returns a changeset. Review and accept it, or rerun with -y to apply without prompting.
A function doesn't show up. It must be public, carry the #[DaggerFunction] attribute, and live on a class marked #[DaggerObject] under src/. Every parameter and the return value need a type hint. Run dagger generate after adding it.
"Argument ... cannot be supported without a typehint" or "cannot be supported without a return type". Add the missing type declaration; the SDK builds the API schema from PHP types, not docblocks.
A missing ListOfType / ReturnsListOfType attribute error. array parameters, fields, and return values must declare their element type with the matching attribute.
A call fails with No class DaggerModule\... exists; run dagger generate. Move the class into its own file under src/, named after the class.
A client class is not found. Run dagger generate. The clients come from the generated sdk/, which must match the scope's clients in dagger.toml.
dagger generate does not regenerate bindings. Look for a .dagger-php-sdk-skip-generate marker in the module or one of its ancestors.
Editor cannot resolve Dagger\... classes or core(). The generated client is not installed locally. Run composer install. vendor/ is gitignored, so this is expected on a fresh clone. If sdk/ is missing or out of date, run dagger generate first.
A check is rejected at registration. Checks take no required arguments other than a Workspace (give every other argument a default or make it nullable). A check must return void. A check that returns a Container fails to load with check MyModule.lint must return Void.
dagger generate refuses a module on the PHP runtime. See Migrate from the built-in PHP runtime.
Next steps
- SDKs overview covers platform concepts that apply to every SDK
- Types
- Generating code
- Quickstart
- PHP SDK repository, whose README documents generation in detail