簡體   English   中英

使用Symfony中的FOSTRestBundle從另一個應用程序中的另一個類調用方法

[英]Call a method from another class in another application with FOSTRestBundle in Symfony

我有類文件ex:Stats.php,當我想給另一個應用程序和類文件ex:Information.php中的另一個方法提供信息的數組時。

文件Stats.php

public function getStats()
{
 $myInformations = // here i want to get information from Information.php
 .
 .
 .
 return $myInformations;
}

在不同的應用中。 文件信息.php

/**
* Get all locales
* @FOS\View()
* @FOS\Get("/locales")
* @param ParamFetcherInterface $paramFetcher
* @return mixed
*/
public function getLocales(ParamFetcherInterface $paramFetcher)
{
  .
  .
  .
  return $locales;
}

我如何從url調用函數getLocales:函數getStatus()中的http://myhost.com/api/locales

當您使用評論中提到的GuzzleBundle時。 您可以將客戶端注入包含getStats()的類,或者將其作為ContainerAware,並通過其容器中的服務ID檢索guzzle-client。 如果您不必為客戶端設置默認選項,即您只想訪問一個網址,您認為所有地方的所有環境始終可用,您可以使用默認值創建一個新客戶端:

$guzzleClient = new GuzzleHttp\Client();

在發送請求部分快速入門中的guzzle文檔中描述了向客戶端發出請求

$response = $guzzleClient->get('http://myhost.com/api/locales')

請求成功后,您可以通過調用以下方法檢索語言環境:

$content = $response->getBody()->getContent();

getBody()為字符串或使用getContent()在此處非常重要。 再次參考Guzzle的文檔,特別是關於使用響應的部分。

例如,如果您發送json編碼的字符串,您可以執行以下操作:

$encodedLocales = $response->getBody()->getContent();
$decodedLocales = json_decode($encodedLocales, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new \Exception(json_last_error_msg());
}

關於這種方法應該說很多東西,比如它很脆弱,因為它依賴於可能連接到不同服務器的工作網絡連接,它不容易測試,傳輸異常沒有得到優雅處理等等。但是對於一個簡單的證明概念或起點這應該足夠了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM