PHP code example of starfederation / datastar-php

1. Go to this page and download the library: Download starfederation/datastar-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

starfederation / datastar-php example snippets


use starfederation\datastar\ServerSentEventGenerator;

// Reads signals from the request.
$signals = ServerSentEventGenerator::readSignals();

use starfederation\datastar\enums\EventType;
use starfederation\datastar\enums\ElementPatchMode;
use starfederation\datastar\ServerSentEventGenerator;

// Creates a new `ServerSentEventGenerator` instance.
$sse = new ServerSentEventGenerator();

// Sends the response headers. 
// If your framework has its own way of sending response headers, manually send the headers returned by `ServerSentEventGenerator::headers()` instead.
$sse->sendHeaders();

// Patches elements into the DOM.
$sse->patchElements('<div></div>', [
    'selector' => '#my-div',
    'mode' => ElementPatchMode::Append,
    'useViewTransition' => true,
]);

// Patches elements into the DOM.
$sse->removeElements('#my-div', [
    'useViewTransition' => true,
]);

// Patches signals.
$sse->patchSignals('{foo: 123}', [
    'onlyIfMissing' => true,
]);

// Executes JavaScript in the browser.
$sse->executeScript('console.log("Hello, world!")', [
    'autoRemove' => true,
    'attributes' => [
        'type' => 'application/javascript',
    ],
]);

// Redirects the browser by setting the location to the provided URI.
$sse->location('/guide');
shell
composer