2016-12-30 6 views
0

저는 Grav CMS를 처음 접했고 양식 데이터를 전달하기 위해 외부 webapi에 게시 요청을하는 가장 좋은 방법을 찾아 내려고했습니다.Grav CMS에서 외부 webapi에 PHP POST를 수행하는 방법은 무엇입니까?

일반적으로 양식 제출 후 실행되고 webapi에 게시물 요청을 수행하는 PHP 코드가 있습니다. 여기서 질문을 읽으십시오. 은 플러그인을 사용하여 모든 사용자 지정 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. 
    } 
}