Skip to content

创建部件 ​

以 customBtn 为例,新建 lib/zin/wg/custombtn/v1.php。加载器按小写名称查找目录,按 $config->zin->wgVerMap 中的部件版本或默认 wgVer 选择文件。默认版本为 1。

定义属性和内部块 ​

php
<?php
declare(strict_types=1);
namespace zin;

class customBtn extends wg
{
    protected static array $defineProps = array
    (
        'text:string',
        'type?:string="button"',
        'disabled?:bool=false'
    );

    protected static array $defineBlocks = array('prefix' => array());

    protected function build(): h
    {
        return button
        (
            set($this->getRestProps()),
            set::type($this->prop('type')),
            set::disabled($this->prop('disabled')),
            $this->block('prefix'),
            $this->prop('text'),
            $this->children()
        );
    }
}

text:string 声明必填属性,? 表示可选,等号后按 JSON 解析默认值。也可以在 protected static array $defaultProps 中通过关联数组为已声明属性赋予默认值。$this->getRestProps() 把调用方给出的 id、类名等其余属性传到按钮上。prefix 和默认子内容的位置由 build() 决定。

使用部件 ​

在 zin 命名空间的视图中,可以直接用加载器创建新部件。

php
createWg('customBtn', array
(
    set::text('继续'),
    to::prefix(span(setClass('icon icon-arrow-right')))
));

若要提供与内置部件一致的函数调用,可按 lib/zin/func.php 的模式定义函数。

php
function customBtn(): customBtn
{
    return createWg('customBtn', func_get_args());
}

如果将函数和类一起写在部件文件里,视图先调用 requireWg('customBtn') 加载定义,随后即可使用 customBtn(set::text('继续'))。

部件的 JS 和 CSS ​

部件需要额外样式或脚本时,在类中返回资源内容。构建节点时,当前上下文只为每个部件类收集一次资源。

php
public static function getPageCSS(): ?string
{
    return file_get_contents(__DIR__ . '/css/v1.css');
}

public static function getPageJS(): ?string
{
    return file_get_contents(__DIR__ . '/js/v1.js');
}

按需在部件目录下添加对应文件,例如 lib/zin/wg/custombtn/css/v1.css。

视图内的组合函数 ​

仅在少数页面使用的结构可以直接定义为函数。下面的函数接收与普通部件相同的参数,将 title 和 items 取出,其余属性继续传给列表。

php
function projectList(mixed ...$args): h
{
    $options = wg(...$args);
    list($title, $items) = $options->prop(array('title', 'items'));
    $rows = array();
    foreach($items as $item)
    {
        $rows[] = li(strong($item['name']), ' ', $item['desc']);
    }

    return ul
    (
        set($options->props->skip(array('title', 'items'))),
        li(setClass('list-heading'), $title),
        $rows,
        $options->children()
    );
}

projectList
(
    set::title('进行中的项目'),
    setClass('my-projects'),
    set::items(array(array('name' => '文档维护', 'desc' => '校对部件示例')))
);

构建钩子、属性读取和节点查询方法见部件基类。