2016-12-30 53 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. 
    } 
}