PHP中的功能组件

v0.0.1 2017-03-15 14:09 UTC

This package is not auto-updated.

Last update: 2024-09-18 20:45:48 UTC


README

功能组件,类似于javascript-land中的功能组件,但使用PHP实现。

特性

  1. 它是“仅仅是PHP”,无需编译
  2. 快速 (初步测试)
  3. 可测试性:它仅仅是返回标记的函数

使用方法

这是一个功能组件库。将标签名称、属性和子组件传递给 h() 函数,它将返回一个表示您请求的标记的格式化字符串。

require 'path/to/h.php'; // or composer (soon)

echo h('h1')([ 'style' => 'color: tomato' ])( 'Hello World' );

// generates: <h1 style="color: tomato">Hello world</h1>

组件

h() 函数在没有传递子组件的情况下返回另一个函数,在这种情况下它返回一个标记字符串。这允许您创建可复用和可组合的样式组件。

$button = h('button')(['class'=>'button button--secondary']);

echo $button('Hello world!');

// generates: <h1 class="button button--secondary">Hello world!</button>

传递的属性将合并到任何先前定义的属性中。

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>

要将子组件添加到现有组件中,可以向返回的函数传递单个 h() 组件,或者一个子组件数组。

$container = h('div')(['class'=>'wrapper']);

echo $container(
  h('h1')('Hello world!')
);

// generates: <div class="wrapper"><h1>Hello world!</h1></div>

echo $container([
  h('h1')('Heading One'),
  $button('Click me!')
]);

/* generates:
<div class="wrapper">
  <h1>Heading One</h1>
  <button class="button button--secondary">Click me!</button>
</div>
*/

您也可以轻松地将数据数组转换为标记

$arr = [
  'Book Title One',
  'Book Title Two'
];

echo $container(
  array_reduce($arr, function($return, $data){
    $return .= h('p')(['style'=>'block'])($data);
    return $return;
  }, '')
);

/* generates:
<div class="wrapper">
  <p style="display: block">Book Title One</p>
  <p style="display: block">Book Title Two</p>
</div>
*/

对于更复杂的组件,创建一个返回格式化 h() 函数的高阶函数

$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:
<table class="wrapper__table">
  <thead>
    <tr>
      <td>tabular content</td>
      <td>tabular content</td>
      <td>tabular content</td>
      <td>tabular content</td>
    </tr>
  </thead>
</table>
*/