Skip to content

Architecture

Knowing how PAM Native is put together makes everything else easier: why a #[State] assignment updates the screen, why animations stay smooth while PHP is busy, and why some work belongs in a native module. This page follows one frame and one tap through the whole system. You do not need any of it to build your first app, but it explains the rules the rest of the documentation relies on.

In short: your PHP code runs inside the app, describes the interface as a tree, and reacts to events. A Rust engine turns that tree into precise mutations, and a thin Kotlin or Swift renderer applies them to real platform views. There is no JavaScript runtime, no WebView and no browser CSS engine.

┌──────────────────────────────┐
│ PHP 8.5 (your app) │ components, state, routes, services
│ render() → element tree │
└──────────────┬───────────────┘
│ PNT1 complete tree / PNP1 patch ▲ events, module results
┌──────────────▼───────────────┐ │
│ Rust engine │ validate, reconcile, layout, diff
└──────────────┬───────────────┘ │
│ PNB1 mutation batch │
┌──────────────▼───────────────┐ │
│ Kotlin / Swift renderer │ Android Views / UIKit controls
│ native modules (camera, …) │────────────────────┘
└──────────────────────────────┘
Layer Owns Does not own
PHP Application logic, state, navigation decisions, what the UI should be. Pixels, layout math, per-frame animation.
Encoder Turning elements into compact binary frames with stable node ids. A C++ port runs on device; the PHP encoder is the reference. Deciding what changed in the views.
Rust engine Validating frames, keeping the retained tree, computing layout, diffing and producing mutation batches. Platform APIs.
Renderer and modules Creating and updating native views, input, scrolling, gestures, media and platform capabilities. Application decisions.

The app process embeds a PHP runtime (8.5 by default, 8.4 optional; see Installation). PHP starts once per process and stays in memory: there is no request per tap, no re-bootstrapping and no server. Your objects, services and caches live as long as the app does.

The device runtime is deliberately small. pam runtime:info lists its compiled extensions (for example ctype, filter, opcache, phar, session, tokenizer and uri). Some features reach PHP another way:

  • Multibyte strings come from a bundled polyfill, so mb_* functions work.
  • Cryptography is provided by the host through the SDK’s crypto API rather than ext-sodium or ext-openssl.
  • Networking, storage, files and devices go through native modules, which run on platform threads and hand PHP only the settled result.

On 32-bit Android ABIs (armeabi-v7a, x86) the runtime keeps 64-bit integers, so colors, ids and timestamps behave exactly as on 64-bit phones.

A component’s render() returns a tree of elements such as Screen, Column, Text and Button. PAM keeps the last committed tree, so each render produces a patch instead of a new interface:

  1. Every element gets a stable node id derived from its position and key.
  2. The encoder compares the new tree with the previous one and sends only the property and structure changes (PNP1). The first frame, or a resynchronization, sends the complete tree (PNT1).
  3. The Rust engine applies the patch to its retained tree, recomputes layout only for dirty nodes and their ancestors, and emits a mutation batch (PNB1).
  4. The renderer creates, updates, moves or removes only the affected views.

Several shortcuts keep this cheap. Components that did not read the changed state keep their previous output. Paint-only changes (a color, an opacity) skip layout. Long lists are virtualized, so only visible rows exist as views. The full list of frame types and hard limits is in Protocol and Limits.

Take the counter from Your First App:

src/Hello.php
Button::make("Taps: {$this->count}")->onPress($this->increment(...)),

When the user taps the button:

  1. Android or UIKit detects the press with its own gesture system and plays the pressed feedback natively.
  2. The renderer queues a press event for the button’s node and wakes PHP.
  3. PHP runs increment(). The assignment to the #[State] property marks the component dirty and schedules one coalesced render; several assignments in the same handler still render once.
  4. The component renders, the encoder produces a patch containing one changed text property, and the engine turns it into one text update.
  5. The renderer sets the new label. Nothing else on screen is touched.

Because the interaction itself (pressed state, scrolling, text editing, gesture tracking) stays native, the UI keeps responding even while PHP is handling an event.

Animations and gestures without PHP per frame

Section titled “Animations and gestures without PHP per frame”

Per-frame work never crosses the bridge. Declarative animations, transitions and compiled worklets run on the platform’s animation clock (ValueAnimator on Android, CADisplayLink on iOS) without calling PHP between frames. PHP describes the motion once and hears about the result. See Animations and Gestures.

Platform features are native modules with an asynchronous contract: PHP sends a small binary map, the module does the work off the UI thread, and PHP receives the result in a callback:

use Pam\Native\Modules\NativeModuleException;
use Pam\Native\Modules\NativeModuleResult;
use Pam\Native\Modules\NativeModules;
NativeModules::call(
'acme.weather',
'today',
['city' => 'Lisbon'],
fn (NativeModuleResult $result) => $this->showForecast($result->values()),
fn (NativeModuleException $error) => $this->showError($error->getMessage()),
);

Most of the time you call a typed PHP API (Http, Storage, SQLite, a plugin’s facade) that wraps a module for you. A module payload is bounded to 1 MiB; larger HTTP bodies reach PHP through a private file instead.

The core ships only what nearly every app needs. Camera, maps, payments, Bluetooth and other optional features are separate pam-native-* plugins that add their own modules and views through Composer; see the Plugin Catalog and Plugins to write your own.

PHP lives as long as the process. When Android recreates the activity, the new activity re-attaches to the same PHP runtime and remounts the retained tree: no PHP code runs again and your state is kept. To keep that rare, the Android host applies rotation, window size, font scale, density, dark mode and locale changes in place, and restores scroll positions and the focused input across the remount.

The app moves between three states, exposed as Pam\Native\AppState: Active, Inactive and Background. Read them reactively with useAppState().

Every component goes through the same ordered lifecycle:

boot() → setup() → mount() → first render → native commit → onMounted() → onFocus()
… renders on state changes …
onBlur() → onUnmounted() → everything created in setup() is released

onFocus() and onBlur() follow navigation: a screen is blurred when another screen covers it, and focused again when it returns. Anything created in setup() (watchers, composables, resources, timers) belongs to the component’s scope and is released automatically at unmount. The full reference is in Component Runtime and State and Lifecycle.

A hidden screen should not poll, animate or download. Tie recurring work to focus:

src/Screens/LivePrices.php
<?php
declare(strict_types=1);
namespace App\Screens;
use Pam\Native\Attributes\State;
use Pam\Native\Component;
use Pam\Native\Element;
use Pam\Native\System\ComponentTimer;
use Pam\Native\UI\Text;
use function Pam\Native\onBlur;
use function Pam\Native\onFocus;
use function Pam\Native\onMounted;
final class LivePrices extends Component
{
#[State]
public int $refreshes = 0;
private ?ComponentTimer $poll = null;
public function setup(): void
{
onMounted(fn () => $this->refresh());
// Poll only while this screen is visible.
onFocus(function (): void {
$this->poll = $this->timers()->every(15_000, fn () => $this->refresh());
});
onBlur(fn () => $this->poll?->cancel());
}
public function refresh(): void
{
$this->refreshes++;
}
public function render(): Element
{
return Text::make("Refreshed {$this->refreshes} times");
}
}

Component timers are also cancelled at unmount, and by default they are suspended while the app is in the background (TimerBackgroundPolicy::Suspend). See Performance for lists, images and other resource rules.

PAM contains failures instead of letting them corrupt the screen:

  • A rejected patch leaves the retained tree untouched; the encoder immediately resends one complete tree, keeping component identity.
  • A host that fails while applying a batch clears its views and asks the engine for a full remount, so later patches never target views that do not exist.
  • Three consecutive failures enter safe mode instead of a restart loop.
  • Uncaught exceptions reach App::onError() listeners and, in debug builds, the error overlay. See Debugging.