定制 ray/web-form-module 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

ray/web-form-module

Composer 安装命令:

composer require ray/web-form-module

包简介

Web Form module for Ray.Di

README 文档

README

Continuous Integration Coding Standards Scrutinizer Code Quality

An aspect oriented web form module powered by Aura.Input and Ray.Di.

Getting Started

Installation

Composer install

$ composer require ray/web-form-module

Module install

use Ray\Di\AbstractModule;
use Ray\WebFormModule\WebFormModule;

class AppModule extends AbstractModule
{
    protected function configure()
    {
        $this->install(new WebFormModule());
    }
}

The legacy Ray\WebFormModule\AuraInputModule class is still available as a thin subclass of WebFormModule for backwards compatibility. New code should prefer WebFormModule.

Usage

Form class

We provide two methods on self-initializing form class, one is init() method where we add an input field on form and apply fileters and rules. The other method method is submit() where it submit data. See more detail at Aura.Input self-initializing forms.

use Ray\WebFormModule\AbstractForm;
use Ray\WebFormModule\SetAntiCsrfTrait;

class MyForm extends AbstractForm
{
    // for anti CSRF
    use SetAntiCsrfTrait;

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        $this->setField('name', 'text')
             ->setAttribs([
                 'id' => 'name'
             ]);
        $this->filter->validate('name')->is('alnum');
        $this->filter->useFieldMessage('name', 'Name must be alphabetic only.');
    }

    /**
     * {@inheritdoc}
     */
    public function submit()
    {
        return $_POST;
    }

    /**
     * {@inheritdoc}
     */
    public function __toString()
    {
        $form = $this->form();
        // name
        $form .= $this->helper->tag('div', ['class' => 'form-group']);
        $form .= $this->helper->tag('label', ['for' => 'name']);
        $form .= 'Name:';
        $form .= $this->helper->tag('/label') . PHP_EOL;
        $form .= $this->input('name');
        $form .= $this->error('name');
        $form .= $this->helper->tag('/div') . PHP_EOL;
        // submit
        $form .= $this->input('submit');
        $form .= $this->helper->tag('/form');

        return $form;
    }
}

Controller

We annotate the methods which web form validation is required with #[FormValidation]. We can specify form object property name with form and failure method name with onFailure.

use Ray\Di\Di\Inject;
use Ray\Di\Di\Named;
use Ray\WebFormModule\Annotation\FormValidation;
use Ray\WebFormModule\FormInterface;

class MyController
{
    /**
     * @var FormInterface
     */
    protected $contactForm;

    #[Inject]
    public function setForm(#[Named("contact_form")] FormInterface $form)
    {
        $this->contactForm = $form;
    }

    #[FormValidation(form: "contactForm", onFailure: "badRequestAction")]
    public function createAction()
    {
        // validation success
        // More detail for `vnd.error+json` can be added with `#[VndError]`.
    }

    public function badRequestAction()
    {
        // validation faild
    }
}

View

You can render entire form html when __toString is given.

  echo $form; // render entire form html

or render input element basis.

  echo $form->input('name'); // <input id="name" type="text" name="name" size="20" maxlength="20" />
  echo $form->error('name'); // "Name must be alphabetic only." or blank.

CSRF Protections

CSRF protection is opt-in and can be enabled through either of two independent paths:

  • Per-form: add use SetAntiCsrfTrait; to the form. AntiCsrfInterface is injected by Ray.Di through the trait's #[Inject] setter, the token field is added in postConstruct(), and every apply() call verifies the token.
  • Per-action: annotate the validated controller method with #[CsrfProtection]. AuraInputInterceptor then injects AntiCsrfInterface into the form before apply() runs.

Either path causes AbstractForm::apply() to throw CsrfViolationException on token mismatch. Without either path, no CSRF check is performed. Combining both paths is harmless but redundant — pick whichever fits your use case.

Per-action — declare CSRF on the controller method:

use Ray\WebFormModule\Annotation\CsrfProtection;
use Ray\WebFormModule\Annotation\FormValidation;

class MyController
{
    #[FormValidation(form: "contactForm")]
    #[CsrfProtection]
    public function createAction()
    {
    }
}

Per-form — declare CSRF on the form itself:

use Ray\WebFormModule\AbstractForm;
use Ray\WebFormModule\SetAntiCsrfTrait;

class MyForm extends AbstractForm
{
    use SetAntiCsrfTrait;
}

You can provide your custom AntiCsrf class. See more detail at Aura.Input

Migration from 0.x

Version 1.0 drops Doctrine Annotations in favour of native PHP 8 Attributes and tightens type declarations. The most common rewrites:

Before (0.x) After (1.0)
@FormValidation(form="f", onFailure="badRequest") #[FormValidation(form: 'f', onFailure: 'badRequest')]
@FormValidation(form="f", antiCsrf=true) #[FormValidation(form: 'f')] + #[CsrfProtection]
@InputValidation(form="f") #[InputValidation(form: 'f')]
@VndError(message="...", logref="...") #[VndError(message: '...', logref: '...')]
new AuraInputInterceptor($injector, $reader) new AuraInputInterceptor($injector) (no Reader argument)
public function input($input) / public function error($input) public function input(string $input): string / error(string $input): string

See CHANGELOG.md for the full list of breaking changes.

Automated migration with Claude Code

The repository ships a Claude Code skill at .claude/skills/migrate-to-1.0/SKILL.md that walks an AI assistant through the rewrites above (annotations → attributes, antiCsrf=true split into #[CsrfProtection], Reader argument removal, FormInterface signature updates). Copy the directory into your consuming project's .claude/skills/ and invoke it via /migrate-to-1.0.

Validation Exception

When we install Ray\WebFormModule\FormVndErrorModule as following,

use Ray\Di\AbstractModule;

class FakeVndErrorModule extends AbstractModule
{
    protected function configure()
    {
        $this->install(new WebFormModule());
        $this->override(new FormVndErrorModule());
    }

A Ray\WebFormModule\Exception\ValidationException will be thrown. We can echo catched exception to get application/vnd.error+json media type.

echo $e->error;

//{
//    "message": "Validation failed",
//    "path": "/path/to/error",
//    "validation_messages": {
//        "name": [
//            "Name must be alphabetic only."
//        ]
//    }
//}

More detail for vnd.error+json can be added with the #[VndError] attribute.

    #[FormValidation(form: "contactForm")]
    #[VndError(message: "foo validation failed", logref: "a1000", path: "/path/to/error", href: ["_self" => "/path/to/error", "help" => "/path/to/help"])]

This optional module is handy for API application.

Demo

$ php -S docs/demo/1.csrf/web.php

ray/web-form-module 适用场景与选型建议

ray/web-form-module 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 22.89k 次下载、GitHub Stars 达 3, 最近一次更新时间为 2015 年 08 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「Ray.Di module」 「web form」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 ray/web-form-module 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 ray/web-form-module 我们能提供哪些服务?
定制开发 / 二次开发

基于 ray/web-form-module 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 22.89k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 9
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 1
  • Forks: 4
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2015-08-24