The ThemedComponent
class provides a simple, fluent API to create and render HTML components in PHP using Twig templates. It integrates with a theming system to load component templates from a designated theme directory, supports dynamic parameter definitions, script injection, and debugging/logging.
Namespace: Skuilplek\Themed
.
Core responsibilities:
components/
subdirectory.make()
, dynamic setters, render()
) for building components.Static Properties
$twig
: Singleton Twig\Environment
used for rendering.$baseTemplatePath
: Optional override for the theme directory.$loggerCallback
: Custom logger for debug messages.$parameterCache
: Caches parsed parameter definitions per template file.Factory Method
public static function make(string $component, array $config = []): self
ThemedComponent
instance for the given template name (e.g., "buttons/button"
).Fluent API via Magic Methods
__call()
and call()
->content()
, ->addClass()
, or arbitrary content setters like ->title('Hello')
.Content and Asset Management
->content(mixed $content)
: Sets main content or an associative array of named slots.->addClass(string $class)
, ->id(string $id)
, ->addAttribute(string $name, string $value)
.->addCss(string $css)
, ->addJavaScript(string $script)
<style>
/<script>
at header/footer via Themed::headerScripts()
and Themed::footerScripts()
.Parameter Parsing
{# ... #}
) in the component template for lines in the form:
- parameterName: type - description
id
, canSee
, addClass
).getParameters(): array
.Initialization (first make()
call):
Themed::getThemePath()
or custom base path.FilesystemLoader
and default filters/functions.component()
Twig function for nested components.Build Phase:
->content()
, ->addClass()
, etc.) to configure the component.Render Phase (->render()
):
canSee
is false.icons/
components).id
, classes
, and attributes
in the template context.Controlled by environment variables:
THEMED_DEBUG=1
enables Twig debug mode and disables cache.THEMED_DEBUG_LEVEL={0..3}
controls verbosity of internal logs.Use ThemedComponent::setLoggerCallback()
to supply a custom logging function.
Throws Exception
if:
use Skuilplek\Themed\ThemedComponent;
// Set custom theme path (optional)
ThemedComponent::setBasePath('/path/to/theme/');
echo ThemedComponent::make('buttons/button')
->addClass('btn-primary')
->content('Click Me')
->render();