PHP code example of slendium / compositor

1. Go to this page and download the library: Download slendium/compositor 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/ */

    

slendium / compositor example snippets


// a component that displays the name property of an object that has to be requested from the database
class ObjectNameComponent implements Component {

	public function __construct(public string $id) { }

	#[Override]
	public function composeHtml(): iterable {
		yield '<div>';
		yield new DatabaseObjectCallback(requestedId: $this->id, callback: function (?object $object) {
			if ($object !== null) {
				yield from [ '<span>', new Icon('my_icon'), $object->name, '</span>' ];
			} else {
				yield '<span class="error">Object not found!<span>';
			}
		});
		yield '</div>';
	}

}

// in practice this would be a framework service or something similar
$objectProvider = get_object_provider();

// set up the HTML compositor, use two-phase to allow optimization of the intermediate representation
// a further optimization would be to ensure objects with different ID's are all requested in a single query
$compositor = CompositorFactory::twoPhase(new class($objectProvider) implements ReplacementProvider {

	/** @var array<string,?object> */
	private array $objectCache = [ ];

	public function __construct(public ObjectProvider $objectProvider) { }

	#[Override]
	public function replace(Localizable|Replaceable|Error $part): iterable {
		if ($part instanceof DatabaseObjectCallback) {
			if (!\array_key_exists($this->objectCache, $part->requestedId)) {
				$this->objectCache[$part->requestedId] = $this->objectProvider->request($part->requestedId);
			}
			return $part->evaluate($this->objectCache[$part->requestedId]);
		}
		return null;
	}

});

// create the tree of components: both components would yield a DatabaseObjectCallback where the first
// instance would trigger a query and the second would reuse the cached object
$tree = new Container([ new ObjectNameComponent('1'), new ObjectDescriptionComponent('1') ]);

// compose the tree
$composition = $compositor->compose($tree);

// if desired, JS and CSS can be generated dynamically based on the components actually in the tree
// more commonly the JS and CSS are