2016-12-30 51 views
0

我是Grav CMS的新手,我试图找出向外部webapi传递表单数据的发布请求的最佳方法。如何在Grav CMS中对外部webapi执行PHP POST?

通常我会在提交表单后执行PHP代码,并会向webapi发送一个post请求,在这里读取一个问题说应该使用插件分隔所有的自定义php逻辑。

我应该使用插件做我的表单发送请求到外部webapi吗?

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

回答

0

您可以为此构建一个插件。下面是一个快速示例代码,您将表单发布到示例页面,在此示例中为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-from-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. 
    } 
}