pre / phpx
0.5.0
2021-07-16 04:13 UTC
Requires
- pre/plugin: ^0.13.0
Requires (Dev)
- phpunit/phpunit: ^5.0|^6.0
README
文档可以在preprocess.io找到。
动机
我想写一个自定义编译器,这个语法吸引了我。它不是JavaScript的替代品,甚至不是一个很好的实现。但我喜欢它。这就足够了。
如果你想写基于组件的代码,而不写JavaScript;那么这可能适合你。
入门
- 克隆仓库
- 安装组件依赖
- 运行测试或执行示例脚本
它应该在PHP 7.2(开发并测试的地方)上工作。如果它不能在7.2上工作,或者你想看到添加的内容,请创建一个问题。
它渲染什么?
目标是使编译器与渲染器解耦。一旦Pre\Phpx\Html渲染器移出,你需要在你的项目中导入它或创建一个自定义的render
函数。Pre\Phpx\Html的render
函数看起来像这样
public function render($name, $props = null) { $props = $this->propsFrom($props); if ($function = globalFunctionMatching($name)) { return call_user_func($function, $props); } if ($class = globalClassMatching($name)) { return (new $class($props))->render(); } // render HTML from a list of allowed elements... return $this->format("..."); }
这意味着你可以定义自己的命名空间函数和类,并在Pre\Phpx\Html的render
函数中使用它们,例如
namespace Example\Application; // don't forget to define or import render // everywhere you use HTML-in-PHP syntax use function Pre\Phpx\Html\render; function MyForm($props) { return ( <form> {$props->showLabel ? <label htmlFor={"email"}>Email</label> : null} <input type={"text"} name={"email"} id={"email"} /> </form> ); } // ...later print render(<Example.Application.MyForm />);
如果你希望组件自动前缀,定义你自己的render
函数,你可以扩展Pre\Phpx\Html的render
函数
namespace Example\Application; use function Pre\Phpx\classMatching; use function Pre\Phpx\functionMatching; use function Pre\Phpx\Html\render as renderHtml; use function Pre\Phpx\Html\propsFrom; define("NAMESPACES", [ // remove this if you only have // namespaced classes and functions "global", // classes and functions will // be loaded from this namespace "Example\\Application", ]); function render($name, $props = null) { $props = propsFrom($props); if ($function = functionMatching(NAMESPACES, $name)) { return call_user_func($function, $props); } if ($class = classMatching(NAMESPACES, $name)) { return (new $class($props))->render(); } return renderHtml($name, $props); } // ...later print render(<MyForm />);
你可以定义组件为函数或类
function MyForm($props) { // render things... } // ...or class MyForm { public function __construct($props) { // ...store and manipulate the props } public function render() { // render things... } }
由于你可以定义一个自定义的渲染函数,你可以决定你的组件可以返回什么。HTML-in-PHP语法转换为以下形式
use function Pre\Phpx\Html\Example\render; function MyForm($props) { return ( <form> {$props->showLabel ? <label htmlFor={"email"}>Email</label> : null} <input type={"text"} name={"email"} id={"email"} /> </form> ); } // ...becomes use function Pre\Phpx\Html\Example\render; function MyForm($props) { return render("form", [ "children" => [ $props->showLabel ? render("label", [ "htmlFor" => "email", "children" => "Email", ]) : null, render("input", [ "type" => "text", "name" => "email", "id" => "email", ]), ], ]); }
你决定你的组件返回什么,以及你的render
函数做什么。Pre\Phpx\Html的render
函数输出HTML字符串,并期望它渲染的组件返回字符串(这样它们可以作为一个子数组中的字符串连接起来)。
返回
null
也将工作。
路线图
- 支持HTML标签警告和重写
- 将HTML渲染器移动到自己的库
- 设置StyleCI和Travis
- 编写更多测试
- 尝试其他渲染器
- 像1999年一样编写文档