reecem/static-form
Composer 安装命令:
composer require reecem/static-form
包简介
Handle static form submissions in Laravel app
README 文档
README
Handle Static form submissions inside your Laravel app from Next.JS and Netlify or any other static site server.
Installation
You can install the package via composer:
composer require reecem/static-form
To install the application you can do the following:
php artisan static-form:install --provider --config
This will install the config file and the service provider, you can though opt for each one separately or use the following:
You can publish the config file with:
php artisan vendor:publish --provider="ReeceM\StaticForm\StaticFormServiceProvider" --tag="static-form-config"
You can publish the Service Provider file with:
php artisan vendor:publish --provider="ReeceM\StaticForm\StaticFormServiceProvider" --tag="static-form-provider"
You will need to add the following to the config/app.php file:
/*
* Package Service Providers...
*/
+ App\Providers\StaticFormServiceProvider::class
You can view the docs here https://static-form.pkgpg.dev
Usage
As an overview, the usage of the current version is that you can use the packages middleware on controllers that you define, this will then use your controller to handle the request data.
Create The Token
The first step is to generate your token, to do that you can use the console command:
php artisan static-form --refresh
This will generate your token, it will show you the plain text version only during that session.
The other way is to call the API endpoint to generate a new one. The API is secured via the Gate that is defined in the App\Providers\StaticFormServiceProvider::class
You can define any logic in there that would allow only authorized people to access the application.
To call the API endpoint, for now you can make a request to the endpoint through a custom UI and javascript code.
| Method | Endpoint | Description |
|---|---|---|
| GET | domain.tld/api/static-form/token | This will return a 200 status and the static-form package version if the toke is found |
| POST | PATCH | domain.tld/api/static-form/token |
The url part that says static-form can be changed and comes from the config key static-form.path
The response for creating a token would be the following JSON with a 201 status:
{
"plain_token": "random_string_that_is_40_characters_long",
"message": "Token Created, please keep this as it is available once"
}
- Make a plugin UI, just deciding on if it should be in package or a separate snippet.
Use the Middleware
To use the middleware, you can define a route using the config file, I do suggest that you use the API endpoint, this is as it is stateless and also would not require the CSRF token.
// routes/api.php Route::group([ 'middleware' => config('static-form.middleware.forms'), ], function () { // A controller that you have created. Route::post('/contact', StaticContactController::class)->name('contact.create'); });
Submitting Forms
On your static site, you can have your contact form. The way of handling the form is done using the API part of the hosting provider.
So for Vercel apps, you can create a new file under the api directory.
For the API part of the code:
// api/contactus.js /** * Create a contact request to the main server. * * @param {http.IncomingMessage} req * @param {*} res */ import { APP_TOKEN, APP_URL } from "../../../lib/constants" export default async function contactus(req, res) { if (req.method !== 'POST') { return res.status(400); } if (req.body?.website) { return res.status(200); } let body = JSON.parse(req.body) let {_token, xsrf} = body.token; delete body.token const request = await fetch( `${APP_URL}/api/static-form/contactus`, { method: 'POST', body: JSON.stringify(body), headers: { 'X-STATIC-FORM': APP_TOKEN, 'Content-Type': 'application/json', 'Accept': 'application/json', "x-requested-with": "XMLHttpRequest", }, } ) if (request.status !== 201 ) { let json = await request.json() throw new Error(json.message || 'Failed to fetch API'); } const json = await request.json() if (json.errors) { console.error(json.errors) throw new Error('Failed to fetch API, json errors') } return res.status(201).json(json.data ?? {}); }
You can try a simple form layout for the frontend:
import React, { useCallback, useEffect, useRef, useState } from 'react' const ContactUs = () => { const [contactName, setContactName] = useState('') const [contactEmail, setContactEmail] = useState('') const [honey, setHoney] = useState('') function handleForm(e) { e.preventDefault() if (honey.length >= 1) { return } let body = { name: contactName, email: contactEmail, } fetch( `${location.origin}/api/contactus`, { method: 'POST', body: JSON.stringify(body) } ) .then(response => { console.debug(response); }) .catch(error => { console.error(error) }) } return ( <> <form onSubmit={handleForm}> <div style={{marginBottom: '0.75rem'}}> <label htmlFor="name">Name</label> <input name="name" id="name" value={contactName} onChange={e => setContactName(e.target.value)} placeholder="Your Name" type="text" /> </div> <div style={{marginBottom: '0.75rem'}}> <label htmlFor="email">Email</label> <input name="email" id="email" value={contactEmail} onChange={e => setContactEmail(e.target.value)} placeholder="Your email" type="email" /> </div> <input style={{display: 'none'}} name="website" value={honey} onChange={e => setHoney(e.target.value)}> <!-- The honeypot field --> <button type="submit">Submit</button> </form> </> ) } export default ContactUs;
Testing
Testing is currently a work in progress, there are some :), I am manually testing it in an actual application to make sure it works though.
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.
reecem/static-form 适用场景与选型建议
reecem/static-form 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8 次下载、GitHub Stars 达 3, 最近一次更新时间为 2021 年 03 月 09 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「laravel」 「netlify」 「nextjs」 「static forms」 「static site forms」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 reecem/static-form 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 reecem/static-form 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 reecem/static-form 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Cecil component theme Netlify CMS
Netlify deployer for the Blitz plugin for Craft CMS.
Netlify deployer for the Blitz plugin for Craft CMS.
NetlifyCMS Wordpress Theme Framework
Trigger your Netlify build hooks with ease
Alfabank REST API integration
统计信息
- 总下载量: 8
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 3
- 点击次数: 13
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-03-09