如何在 Grav CMS 中对外部 webapi 执行 PHP POST?

How to do a PHP POST to external webapi in Grav CMS?

我是 Grav CMS 的新手,我正在尝试找出向外部 webapi 发出 post 请求以传递表单数据的最佳方法。

通常我会有 PHP 在提交表单后执行的代码,并将向 webapi 发出 post 请求,在这里阅读一个问题 https://getgrav.org/forum#!/getgrav/general:adding-php-code-in-grav 说应该将所有使用插件的自定义 php 逻辑。

我是否应该使用插件向外部 webapi 发送表单 post 请求?

我只是想确保我使用插件的方向正确。

您可以为此构建一个插件。这是一个快速示例代码,您 post 您的表单到示例页面,在这个示例中是 yoursite.com/my-form-route

<?php
namespace Grav\Plugin;

use \Grav\Common\Plugin;

class MyAPIPlugin extends Plugin
{
    public static function getSubscribedEvents()
    {
        return [
            'onPluginsInitialized' => ['onPluginsInitialized', 0]
        ];
    }

    public function onPluginsInitialized()
    {
        if ($this->isAdmin())
            return;

        $this->enable([
            'onPageInitialized' => ['onPageInitialized', 0],
        ]);
    }

    public function onPageInitialized()
    {
        // This route should be set in the plugin's setting instead of hard-code here.
        $myFormRoute = 'my-form-route';

        $page = $this->grav['page'];
        $currentPageRoute = $page->route();

        // This is not the page containing my form. Skip and render the page as normal.
        if ($myFormRoute != $currentPageRoute)
            return;

        // This is page containing my form, check if there is submitted data in $_POST and send it to external API.
        if (!isset($_POST['my_form']))
            return;

        // Send $_POST['my_form'] to external API here.
    }
}