A fetherweight class for generating predefined HTML or autonymous web components.
While developing the user interfaces for our various online applications we managed to consolidate the basic logic for generating HTML elements, web components, and complete pages of content. This consolidation resulted in the creation of a single featherweight class we call Component by 8fold, which is available via Composer and Packagist and GitHub.
It is the backbone for our other web user interface packages.
$ composer require 8fold/php-html-component
There is only one public method,
build. It accepts a configuration dictionary.
Eightfold\HtmlComponent\Component::build([ 'element' => 'my-component', 'content' => 'Hello, World!', 'attributes' => [ 'id' => 'something-unique', 'class' => 'my awesome styles' ] ]);
<my-component id="something-unique" clas="my awesome styles"> Hello, World! </my-component>
Extending a known element:
Eightfold\HtmlComponent\Component::build([ 'element' => 'my-component', 'extends' => 'p', 'content' => 'Hello, World!' ]);
<p is="my-component">Hello, World!</p>
The Component class only understands the following keys:
element: The string to place in the opening and closing tags.
extends: Whether this element extends another, known element. Ex.
role: The role the component plays in the document or application.
omit-closing-tag: true|false (Default is false.) Whether the element has a
closing tag. Ex.
attributes: Dictionary of key value pairs to place attributes inside the
- content: string|array Accepts a single string or an array of component configurations.
The only opinions made by the Component class is the order of the primary identifying attributes, in this order:
- extension (is),
After that, the attributes will appear in the order in which they are received. The content will then be processed. Then capped off with a closing tag, if applicable.
The Component class is designed to be extended in order to reduce the complexity needed by developers to create more compound elements and components. There are two override points:
buildmethod itself. This method calls three methods in turn to generate a complete HTML string: opening, closing, and content.
contentmethod is the second override point. This method focuses on the
contentkey of the configuration. If the value is an array, it will call the
Therefore, it is recommended that you use your
build override to clean up the configuration any way you see fit, then call
parent::. Further, if you are creating a complex library of elements and components, it is recommended that you override the
content method as well, and most likely not call
parent::. See 8fold Elements for a production implementation.