Skip to content

Storage

A mobile application keeps several kinds of data on the device: a few user preferences, the state a screen should come back to, documents the user created, downloaded media, and credentials such as a refresh token. Each has a different lifetime and a different security requirement, so PAM Native gives each one its own home instead of a single “save anything” API.

You want to keep… Use Lives in
Small settings (theme, last tab, onboarding flag) Storage Platform preferences
State a component or screen should restore #[State(persist: true)], Restorable PAM state storage
Shared application state Global store persistence PAM state storage
Structured records you query SQLite Private database directory
Documents, imports, downloads Files Private pam-files directory
Image and media cache Caches Platform cache directory
Tokens and other small secrets SecureStorage Android Keystore / Apple Keychain

Everything on this page is private to your application. Nothing is written to shared external storage, and absolute device paths never reach PHP.

Pam\Native\Storage\Storage stores string values by key. Android backs it with private SharedPreferences; iOS uses UserDefaults. Both calls are asynchronous: the result arrives in a callback once the native worker has read or committed the value.

src/Settings/AppearancePreference.php
<?php
declare(strict_types=1);
namespace App\Settings;
use Closure;
use Pam\Native\Storage\Storage;
final class AppearancePreference
{
private const KEY = 'settings.appearance';
/** @param Closure(string): void $callback */
public static function load(Closure $callback): void
{
Storage::get(self::KEY, static function (?string $value) use ($callback): void {
$callback($value ?? 'system');
});
}
public static function save(string $mode, ?Closure $saved = null): void
{
Storage::set(self::KEY, $mode, $saved);
}
}

Storage::get() passes null when the key has never been written. To store structured data, encode it yourself:

Storage::set('onboarding.progress', json_encode([
'step' => 3,
'skipped' => false,
], JSON_THROW_ON_ERROR));
Storage::get('onboarding.progress', function (?string $json): void {
$progress = $json === null
? ['step' => 1, 'skipped' => false]
: json_decode($json, true, flags: JSON_THROW_ON_ERROR);
});
  • A value is at most 256 KiB (Storage::MAX_VALUE_BYTES); a larger write is rejected as a whole.
  • Any string works as a key. Storage::safeKey() is applied to every key: keys made of A-Z, a-z, 0-9, _, ., - (up to 128 characters) pass unchanged, other characters become -, and longer keys are shortened with a hash suffix.
  • A native failure (oversized value, failed commit) is raised as a NativeModuleException from the callback path. Pass onError to handle it instead:
use Pam\Native\Modules\NativeModuleException;
use Pam\Native\Storage\Storage;
Storage::set(
'drafts.comment',
$this->draft,
onError: fn (NativeModuleException $error) => $this->saveFailed = true,
);

When you cache a feed or a profile in Storage, StorageBudget encodes it so it always fits: lists keep their first items, maps their most recent entries, and an oversized object becomes an empty string (no cache) instead of a failed write.

use Pam\Native\Storage\Storage;
use Pam\Native\Storage\StorageBudget;
Storage::set('feed.page', StorageBudget::encodeList($posts, limit: 48)); // newest first
Storage::set('profile.me', StorageBudget::encodeObject($profile));

For state that belongs to one component — the selected tab, a draft, a scroll filter — mark the property as persisted and let PAM save and restore it:

src/Screens/InboxScreen.php
use Pam\Native\Attributes\State;
use Pam\Native\Component;
final class InboxScreen extends Component
{
#[State(persist: true)]
public int $selectedTab = 1;
#[State]
public string $search = '';
// render() ...
}

Only properties declared with persist: true are written; the rest stay in memory. For full control, implement Pam\Native\Restorable:

src/Screens/ComposerScreen.php
use Pam\Native\Component;
use Pam\Native\Restorable;
final class ComposerScreen extends Component implements Restorable
{
private string $draft = '';
public function stateKey(): string
{
return 'composer.draft';
}
public function saveState(): array
{
return ['draft' => $this->draft];
}
public function restoreState(array $state): void
{
$this->draft = (string) ($state['draft'] ?? '');
}
}

PAM persists Restorable components on lifecycle transitions and only when the serialized state actually changed. See component runtime for the full lifecycle.

A global store persists only the keys returned by its persist() method. Stores support versioned migrations and authenticated encryption through EncryptedStatePersistence. Use a store when several screens share the same data, such as the signed-in user’s profile or a cart.

Pam\Native\System\Files reads and writes inside the application’s private pam-files directory. Every path is relative to that directory: absolute paths, .., empty segments, and control characters are rejected.

src/Notes/NoteFiles.php
use Pam\Native\FileReference;
use Pam\Native\System\Files;
// Write (at most 1 MiB per call).
Files::write('notes/welcome.md', "# Welcome\n", function (): void {
// Written.
});
// Read it back.
Files::read('notes/welcome.md', function (string $contents): void {
$this->body = $contents;
});
// Inspect and list.
Files::stat('notes/welcome.md', fn (FileReference $file) => $this->size = $file->size);
Files::list('notes', function (array $files): void {
$this->notes = array_map(fn (FileReference $file) => $file->name, $files);
});
// Check, move, copy, create folders.
Files::exists('notes/welcome.md', fn (bool $exists) => $this->hasWelcome = $exists);
Files::makeDirectory('notes/archive');
// Remove (a missing file counts as deleted).
Files::delete('notes/welcome.md');

A FileReference exposes path, name, mimeType, and size. Pass $file->uri() (a pam-file:/// URI) to Image or MediaPlayer so the renderer reads the file directly — the bytes never cross the PHP bridge.

read() and write() move at most 1 MiB per call through the bridge. For anything larger, let native code do the work:

Task API
Download to a file Files::download() / Files::downloadWithProgress() (HTTPS, 64 MiB default cap)
Upload a file Http::upload() — see HTTP networking
Hash a file Files::sha256()
Copy a bundled asset Files::copyAsset()
Open with another app Files::open()
Pick or capture Files and media
Durable background transfer Background Transfer
src/Media/PodcastDownloader.php
use Pam\Native\FileDownloadProgress;
use Pam\Native\FileReference;
use Pam\Native\System\Files;
$this->download = Files::downloadWithProgress(
url: 'https://cdn.example.com/episodes/42.m4a',
destination: 'episodes/42.m4a',
callback: fn (FileReference $file) => $this->episodePath = $file->path,
progress: fn (FileDownloadProgress $progress) => $this->progress = $progress->fraction(),
maximumBytes: 50 * 1024 * 1024,
failure: fn (string $message) => $this->error = $message,
);
// When the screen goes away:
Files::cancelDownload($this->download);

Downloads accept HTTPS only, reject URLs with embedded credentials, and replace the destination atomically after a successful transfer.

Images and streamed media are cached by the renderer in the platform cache directory, which the operating system may purge under storage pressure. Show the user what the cache costs and let them clear it:

src/Settings/StorageSettings.php
use Pam\Native\CacheUsage;
use Pam\Native\System\Caches;
Caches::usage(function (CacheUsage $usage): void {
$this->cacheMegabytes = round($usage->totalBytes / 1_048_576, 1);
});
Caches::clear(
callback: fn (CacheUsage $after) => $this->freed = $after->freedBytes,
preserveOffline: true,
imports: true,
);

CacheUsage reports fileCount, imageBytes, mediaBytes, temporaryBytes, importBytes, totalBytes, and freedBytes. Keep preserveOffline: true (the default) so media the user pinned for offline use survives a cleanup; imports: true also removes copies made by pickers and imports.

For your own disposable files, write them under Files::cachePath('name') (the cache folder inside the sandbox, Files::CACHE_DIRECTORY): Caches::clear() empties it. Per-image and per-video cache policies are covered in Images and cache and Video and audio.

Secrets do not belong in preferences, files, or SQLite. The core Pam\Native\Storage\SecureStorage keeps small secrets — session tokens, PIN hashes, keys — in the platform secure store: AES-GCM with a non-exportable Android Keystore key, or the iOS Keychain (this device only, while unlocked).

src/Auth/SessionToken.php
<?php
declare(strict_types=1);
namespace App\Auth;
use Closure;
use Pam\Native\Storage\SecureStorage;
final class SessionToken
{
private const KEY = 'session.token';
public static function remember(string $token, ?Closure $saved = null): void
{
SecureStorage::set(self::KEY, $token, $saved); // $saved receives bool
}
/** @param Closure(?string): void $callback */
public static function restore(Closure $callback): void
{
SecureStorage::get(self::KEY, $callback); // null when absent or unreadable
}
public static function forget(): void
{
SecureStorage::delete(self::KEY);
}
}

Keys are 1–256 characters and values at most 65,536 characters. get() passes null when the key has no value or cannot be read.

For refresh tokens with an explicit accessibility policy, typed result states, and OAuth 2.1 PKCE, install the pushinbr/pam-native-auth plugin:

Terminal window
pam composer require pushinbr/pam-native-auth
pam doctor --fix
use Pam\Native\Auth\AuthOperationState;
use Pam\Native\Auth\AuthVault;
use Pam\Native\Auth\CredentialAccessibility;
(new AuthVault())->store(
'session.refresh-token',
$refreshToken,
fn (AuthOperationState $state, ?string $error) => $this->stored = $state === AuthOperationState::Succeeded,
CredentialAccessibility::DeviceOnly,
);

AuthVault also has retrieve(), exists(), and delete(). AuthOperationState is Succeeded, NotFound, Denied, or Failed; CredentialAccessibility is AfterFirstUnlock, WhenUnlocked, or DeviceOnly (the default). The plugin also provides biometrics and screen privacy.

Data Location
Storage SharedPreferences named pam-native (private mode)
Files filesDir/pam-files
SQLite filesDir/pam-databases
Image and media cache cacheDir (purgeable by the system)
SecureStorage Keystore-sealed (AES-GCM) private storage

Uninstalling the application removes all of it. Device-only Keychain items never migrate to another device, and Android data extraction rules exclude the app’s data from cloud backup and device transfer.