Skip to content

Instantly share code, notes, and snippets.

@Shigetorum635
Created January 24, 2022 07:41
Show Gist options
  • Save Shigetorum635/1f4b07a031165392ce8bd47b55975c50 to your computer and use it in GitHub Desktop.
Save Shigetorum635/1f4b07a031165392ce8bd47b55975c50 to your computer and use it in GitHub Desktop.
A PHP Class to easily create components in vanilla PHP.
<?php
class RouteComponents
{
public $name;
public $components = [];
public function __construct($name)
{
$this->name = $name;
}
public function component(string $name, array $slots, bool $sanitize = false)
{
if (!array_key_exists($name, $this->components) || (array_keys($slots) === range(0, count($slots) - 1))) {
return;
}
$component = $this->components[$name];
if ($sanitize) {
foreach ($slots as $name => $value) {
$component = str_replace('{' . $name . '}', htmlspecialchars($value), $component);
}
} else {
foreach ($slots as $name => $value) {
$component = str_replace('{' . $name . '}', $value, $component);
}
}
echo $component;
}
public function addComponent($name, $html)
{
$this->components[$name] = $html;
}
}
$components = new RouteComponents('myComponents');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment