Documentation menu

Actions

An action is a PHP callback the browser can run. A click or a form submit makes Datastar POST to the action's URL with the tab's signals, your callback runs, and what it changed goes back over the tab's SSE stream.

Creating an action

$increment = $c->action(function (Context $c) use ($count): void {
    $count->setValue($count->int() + 1);
}, 'increment');

The callback receives the context of the tab that posted it. The second argument is the action's name: it goes into the URL, and a template gets the action under it. Unnamed actions are numbered action0, action1 and so on, in the order the handler registers them. action() takes no third argument: an action runs for the tab that posts it, and state that tabs share lives in signals with a scope (see Scopes).

Action URL

Pass the URL to the view:

$increment->url();  // '/_action/increment'

and bind it to a Datastar event attribute. In a Twig template the action is a variable under its name:

<button data-on:click="@post('{{ increment.url }}')">+1</button>
Always use @post() for actions. GET /_action/… returns 405 Method Not Allowed. Accepting actions over GET would allow top-level browser navigation (a link or redirect from any origin) to trigger state changes without the user's intent, a classic CSRF vector. Use @post(), @patch(), @put(), or @delete(): all of these require an explicit browser fetch() call, which the browser's cross-origin policy controls. @get() is fine for the SSE endpoint (/_sse), just not for actions.

What goes back to the browser

When the action returns, the TAB signals it changed go to its tab, also when it throws. That covers the page and its components, so an action that only changes signals needs no sync call:

$c->action(function () use ($label): void {
    $label->setValue('Saved!'); // reaches the tab when the action returns
}, 'save');

The view does not render for that. Call $c->sync() when the action changes what the view renders, such as rows it reads from a database:

$c->action(function (Context $c) use ($todos, $draft): void {
    $todos->add($draft->string());
    $draft->setValue('');
    $c->sync(); // render the list again
}, 'add');

A write to a scoped signal broadcasts its scope, which renders every tab in it, the acting tab included. A scoped signal declared with autoBroadcast: false goes nowhere until you call $c->syncSignals() or $app->broadcast(). To render other tabs after a change outside signals, broadcast their scope; see Broadcasting.

Reading request data

Read the query string and the POST body with $c->input() inside the callback, and an uploaded file with $c->file(). OpenSwoole does not fill $_POST, $_GET or $_FILES:

$vote = $c->action(function (Context $c) use ($app): void {
    $option = $c->input('option');
    if (!in_array($option, ['a', 'b', 'c'], true)) {
        return; // ignore unknown values
    }
    $app->incrementGlobalState('vote_' . $option);
    $app->broadcast(Scope::routeScope('/poll'));
}, 'vote');
<!-- Pass option as query param -->
<button data-on:click="@post('{{ vote.url }}?option=a')">Vote A</button>

In the page handler, $c->input() reads the page's query string.

Each action reads its own request

$c->input(), $c->file(), $c->cookie() and $c->getRequestAttribute() return the values of the request that posted the action, and a cookie from $c->setCookie(), like the new session cookie of $c->regenerateSession(), goes out with that action's response, whatever its status. This holds when two actions of one tab run at once and one of them waits on I/O.

  • A $c->spawn() task keeps the request of the action that started it. Once the action has answered, $c->file() returns null, because OpenSwoole deletes the upload's temporary file with the request: move the file in the action. A cookie the task sets after that goes out with the tab's next action response.
  • Code outside an action, such as a timer, the SSE connect or a broadcast render, reads the page request. A cookie it sets goes out with the tab's next action response.
  • Signals are the tab's state, not the request's: an action that waits sees the values the browser sent with a later action of the tab.
  • Request attributes in an action come from global middleware, which runs on actions. Per-route middleware runs on page loads.

Logging in

An action that logs a visitor in calls $c->regenerateSession() before it writes the login. The session gets a new cookie with the action's response, so a cookie someone planted or read before the login no longer reaches it, and it keeps its id, its data, its SESSION signals and its other tabs. The old cookie opens no page from then on, and for 2 seconds it still reaches the actions and streams of tabs that exist, for requests already on their way:

$c->action(function (Context $c) use ($users, $username, $password, $error): void {
    $user = $users->check($username->string(), $password->string());
    if ($user === null) {
        $error->setValue('Invalid username or password.');

        return;
    }

    $c->regenerateSession();
    $c->setSessionData('user_id', $user->id);
    $c->execScript("window.location.href = '/dashboard'");
}, 'login');

A logout calls it too, with $c->clearSessionData(). Middleware and route() handlers call $app->regenerateSession($request); see Session rotation.

Multiple actions per context

A context can have as many actions as needed. Each gets its own URL:

$inc   = $c->action(fn () => $count->increment(), 'inc');
$dec   = $c->action(fn () => $count->increment(-1), 'dec');
$reset = $c->action(fn () => $count->setValue(0), 'reset');

Registering a second action under the same name in one context replaces the first and logs a warning.

Events, patches and scripts

Besides signals and the view, an action can send the page:

  • $c->dispatch($event, $detail): a CustomEvent on window, its detail JSON-encoded, for a toast and the like.
  • $c->patchElements($html, $selector, $mode): HTML outside the view, such as a line appended to a log. See Views.
  • $c->execScript($js): a script, for what the other two do not cover.
$c->action(function (Context $c) use ($notes, $note): void {
    $notes->save($note->string());
    $c->dispatch('toast', ['text' => 'Saved']);
}, 'save');
<div id="toast" data-on:toast__window="el.textContent = evt.detail.text"></div>

They reach the tab in the order the action sent them, and none is dropped for a client that falls behind. A component's go to its page.

Downloads

$c->download($source, $filename, $mimeType) returns a one-shot URL that sends a file over plain HTTP, outside the SSE stream. The source is a file path, or a callable that returns the content or yields it in chunks when the browser fetches the URL, so a large export never sits in memory:

$c->action(function (Context $c) use ($orders): void {
    $url = $c->download(function () use ($orders): \Generator {
        foreach ($orders->all() as $order) {
            yield implode(',', $order) . "\n";
        }
    }, 'orders.csv', 'text/csv; charset=utf-8');

    $c->execScript('window.location = ' . json_encode($url));
}, 'export');

The URL works once, for the tab's session, while its context lives, and a tab keeps its newest 100. A source that throws reaches onError() as ErrorPhase::Render, and the browser sees the download fail.

Waiting on I/O

A worker serves all its tabs from one thread. An action that waits on a database query, an HTTP call over PHP streams or a sleep suspends only its own coroutine, through OpenSwoole's coroutine hooks, and the worker serves other requests meanwhile. A call no hook covers blocks the worker until it returns, and so does a curl request on libcurl 8.20 or newer. See Coroutine hooks.

Work that outlasts the action

$c->spawn($task) runs work in a coroutine of its own, so the action answers at once. The task receives the context. Only an action sends its changed signals by itself, so a task calls syncSignals() or sync():

$c->action(function (Context $c) use ($status, $report): void {
    $status->setValue('running'); // goes out when the action returns

    $c->spawn(function (Context $c) use ($status, $report): void {
        $report->build();         // slow work
        $status->setValue('done');
        $c->syncSignals();
    });
}, 'run');

A task keeps running when its tab goes for good. From then on $c->isDestroyed() is true and its syncs, patches and downloads do nothing, so it finishes without guards; a long task checks isDestroyed() to stop early. A throw from a task is logged and reaches onError() as ErrorPhase::Task, and a stopping worker waits for running tasks.

Requests that cancel each other

Datastar cancels an in-flight request when the page sends another one with the same method and URL, from any element. A request cancelled before it reaches the server never runs its action. One that has reached php-via still runs, and its patches arrive over the SSE stream as usual. Cancellation suits a value where the latest post wins, such as a slider. Where every request counts, or where two elements post the same action URL for different reasons, such as the Enter key in a field and a send button, tell the requests apart with a query string (Datastar compares the URL as written in the expression), or pass requestCancellation: 'disabled':

<input data-bind="{{ message.id }}"
    data-on:keydown="evt.key === 'Enter' && @post('{{ send.url }}?from=enter')">
<button data-on:click="@post('{{ send.url }}?from=button')">Send</button>

<!-- every click counts, so none may cancel another -->
<button data-on:click="@post('{{ paint.url }}', {requestCancellation: 'disabled'})">Paint</button>

When an action throws

A throw from an action, a view or a timer never takes the worker down. An action that throws any \Throwable answers 500 Action failed, its tab still gets the signals it changed before the throw, and the error is logged with its class, message and file:line. A page whose handler or render throws answers 500, with the exception in dev mode, and its context is torn down. A view that throws during a broadcast skips that one tab, and the other tabs still get the frame. A per-tab $c->setInterval() keeps ticking after a throw.

$app->onError() sees each of these throws, to report them:

use Mbolli\PhpVia\Context;
use Mbolli\PhpVia\ErrorPhase;

$app->onError(function (\Throwable $e, ?Context $c, ErrorPhase $phase, ?string $action): void {
    error_log(sprintf('[%s] %s: %s', $phase->value, $action ?? '-', $e->getMessage()));

    if ($phase === ErrorPhase::Action) {
        $c?->getSignal('error')?->setValue('Saving failed. Try again.');
    }
});

The phase says where the throw came from: Action, Render (a page handler, a view or a download() source), Timer, Task (a spawn() task) or Route (a route() handler). For an action, $c is the tab's page context, also for a component's action, and $action the action's id. The callback only observes: the action still answers 500. It runs before the changed signals go out, so a signal it writes reaches the tab with them, and before the response, so a slow report delays the 500. Throws from onClientConnect(), onCleanup() and the other lifecycle callbacks are only logged.

Actions with several workers

With withWorkerNum() above 1, a tab lives on the worker that holds its SSE stream, and an action can reach another worker. That worker passes the action to the tab's worker and sends back its answer, cookies included, so the action always runs on the tab's own context. It waits up to withContextTimeouts(forwardMs: ...), 60 seconds by default, and then answers 504; the action may still finish. download() URLs go the same way. See Same machine.

Endpoints without a page

An action belongs to a tab. For a JSON endpoint, a webhook or an MCP server, register a PSR-15 handler with $app->route(). It runs behind the global middleware and its own, with no context, shell or template:

use Nyholm\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

$app->route('GET', '/api/votes', new class($app) implements RequestHandlerInterface {
    public function __construct(private Via $app) {}

    public function handle(ServerRequestInterface $request): ResponseInterface {
        $body = json_encode(['votes' => $this->app->globalState('votes', 0)]);

        return new Response(200, ['Content-Type' => 'application/json'], $body);
    }
});

The request carries the session id in its via.session attribute and each path parameter as an attribute of its name. php-via checks no Origin header there, so give a route that changes state CSRF or auth middleware. A throw answers 500 and reaches onError() as ErrorPhase::Route.

Next steps