h
Functional components a la javascript-land, but in PHP., (*1)
Features
It's "just PHP", no compiling
Fast (preliminary tests)
Testable: it's just functions that return markup
Usage
This is a functional component library. Pass tag name, attributes, and children to the h() function and it will return a formatted string representing the markup you've requested., (*2)
require 'path/to/h.php'; // or composer (soon)
echo h('h1')([ 'style' => 'color: tomato' ])( 'Hello World' );
// generates:
Hello world
Components
The h() function returns another function unless it has been passed children, in which case it returns a string of markup. This allows you to create styled components for later reuse and composition., (*3)
$button = h('button')(['class'=>'button button--secondary']);
echo $button('Hello world!');
// generates:
<
h1 class="button button--secondary">Hello world!</button>
Passed attributes are merged with any previously defined attributes., (*4)
echo $button([
'class'=>'button--rounded',
'style'=>'font-style: italic'
])('Hello world!');
// generates: <button class="button button--secondary button--rounded" style="font-style: italic">Hello world!</button>
To add children to an existing component, either pass a single h() component to the returned function, or an array of children., (*5)
$container = h('div')(['class'=>'wrapper']);
echo $container(
h('h1')('Hello world!')
);
// generates:
Hello world!
echo $container([
h('h1')('Heading One'),
$button('Click me!')
]);
/* generates:
Heading One
Click me!
*/
You can also easily turn arrays of data into markup:, (*6)
$arr = [
'Book Title One',
'Book Title Two'
];
echo $container(
array_reduce($arr, function($return, $data){
$return .= h('p')(['style'=>'block'])($data);
return $return;
}, '')
);
/* generates:
Book Title One, (*7)
Book Title Two, (*8)
*/
For more complex components, create a higher order function that returns a formatted h() function:, (*9)
$table = function( $children ){
return h('table')(['class'=>'wrapper__table'])(
h('thead')(
h('tr')( $children )
)
);
};
echo $table([
h('td')('tabular content'),
h('td')('tabular content'),
h('td')('tabular content'),
h('td')('tabular content')
]);
/* generates:
tabular content
tabular content
tabular content
tabular content
*/