当我想给另一个应用程序和类文件ex:Information.php中的另一个方法提供信息的数组时,我有类文件ex:Stats.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;
}
我如何从函数getStatus()中的url:http://myhost.com/api/locales调用函数getLocales?
答案 0 :(得分:0)
当您使用评论中提到的GuzzleBundle时。您可以将客户端注入包含getStats()
的类,或者将其设置为ContainerAware,并通过其容器中的服务ID检索guzzle-client。如果您不必为客户端设置默认选项,即您只想访问一个网址,您认为所有地方的所有环境始终可用,您只需创建一个具有默认值的新客户端:
$guzzleClient = new GuzzleHttp\Client();
Quickstart in section Sending Requests:
中的guzzle文档中描述了向客户提出请求$response = $guzzleClient->get('http://myhost.com/api/locales')
请求成功后,您可以通过调用:
来检索语言环境$content = $response->getBody()->getContent();
将getBody()
投射到字符串或使用getContent()
非常重要。再次参考Guzzle的文档,特别是关于using responses的部分。
例如,如果您发送一个json编码的字符串,您可以执行以下操作:
$encodedLocales = $response->getBody()->getContent();
$decodedLocales = json_decode($encodedLocales, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \Exception(json_last_error_msg());
}
关于这种方法应该说很多东西,比如它很脆弱,因为它依赖于可能连接到不同服务器的工作网络连接,它不容易测试,传输异常不能正常处理等等。但是对于一个简单的概念证明或起点就足够了。