A small CakePHP 5 application showing how to integrate Datastar to build reactive views while rendering all the HTML on the server.
The demo is a contacts page with:
- Live search: a debounced
@get()returning a plain HTML element that Datastar morphs into the page. - Add a contact: a
@post()with CakePHP validation errors shown inline through signals, and the list refreshed in the same response. - Delete: a
@delete()answered with a singleremoveevent. - A long-running job: a
@post()that keeps the connection open and streams a progress bar and a log using Server-Sent Events.
You need DDEV (and Docker). Then:
git clone git@github.com:CakeDC/cakephp-datastar-example.git
cd cakephp-datastar-example
ddev start
ddev launchThat's it. On every ddev start a hook (see .ddev/config.yaml) runs composer install, creates the test database, runs the migrations and seeds a few contacts (only if the table is empty). The demo is the home page, https://datastar-cakephp-example.ddev.site (the project name comes from .ddev/config.yaml, not from the folder name).
Stack: PHP 8.5, nginx-fpm, Postgres 18, CakePHP 5.4, Datastar 1.0.5 (loaded from a CDN).
ddev exec vendor/bin/phpunit
ddev exec vendor/bin/phpcsAny PHP 8.2+ setup works. Run composer install (it creates config/app_local.php from config/app_local.example.php), then point the app to your database with DATABASE_URL and DATABASE_TEST_URL, for example postgres://user:pass@localhost/datastar, and run:
bin/cake migrations migrate
bin/cake seeds run Contacts
bin/cake serverIf you use MySQL instead of Postgres, remove the 'encoding' => 'utf8' lines from config/app_local.php.
| File | What it does |
|---|---|
src/Controller/Component/DatastarComponent.php |
Reads the signals sent by Datastar and builds the SSE events (patchElements(), patchSignals()), as a normal response (respond()) or a stream (stream()). |
src/View/Helper/DatastarHelper.php |
Builds @get(), @post(), ... expressions from CakePHP routes, adding the CSRF token header. |
src/Controller/ContactsController.php |
The four interactions described above. |
templates/Contacts/index.php |
The page: signals, bindings, indicators and actions. |
templates/element/Contacts/list.php |
The list, used for the full page and for every partial update. |
tests/TestCase/Controller/ContactsControllerTest.php |
Integration tests asserting the HTML fragment and the SSE output. |
- Datastar requests carry the CSRF token in a
X-CSRF-Tokenheader, added by the helper. - Streaming responses send
X-Accel-Buffering: noso nginx doesn't buffer them, and close the session first so other requests from the same user aren't blocked. - An open stream keeps a PHP-FPM worker busy while it runs. Fine for a demo or a progress bar, but plan for it if you need many long lived connections.
MIT