Created
January 24, 2022 07:41
-
-
Save Shigetorum635/1f4b07a031165392ce8bd47b55975c50 to your computer and use it in GitHub Desktop.
A PHP Class to easily create components in vanilla PHP.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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