[英]Call a method from another class in another application with FOSTRestBundle in Symfony
I have the class file ex: Stats.php when i want to give an array with information from another method in another application and class file ex: Information.php. 我有类文件ex:Stats.php,当我想给另一个应用程序和类文件ex:Information.php中的另一个方法提供信息的数组时。
File Stats.php 文件Stats.php
public function getStats()
{
$myInformations = // here i want to get information from Information.php
.
.
.
return $myInformations;
}
In different application. 在不同的应用中。 File Informations.php
文件信息.php
/**
* Get all locales
* @FOS\View()
* @FOS\Get("/locales")
* @param ParamFetcherInterface $paramFetcher
* @return mixed
*/
public function getLocales(ParamFetcherInterface $paramFetcher)
{
.
.
.
return $locales;
}
How I call function getLocales from url: http://myhost.com/api/locales in function getStatus()? 我如何从url调用函数getLocales:函数getStatus()中的http://myhost.com/api/locales ?
When you are using the GuzzleBundle as mentioned in your comment. 当您使用评论中提到的GuzzleBundle时。 You can just inject a client into the class containing
getStats()
or by making it ContainerAware and retrieving the guzzle-client by its service id from the container. 您可以将客户端注入包含
getStats()
的类,或者将其作为ContainerAware,并通过其容器中的服务ID检索guzzle-client。 If you don't have to set default options for your client, ie you just want to access a url you assume is always available for all environments from all places you could just create a new client with default values: 如果您不必为客户端设置默认选项,即您只想访问一个网址,您认为所有地方的所有环境始终可用,您可以使用默认值创建一个新客户端:
$guzzleClient = new GuzzleHttp\Client();
Making a request with the client is described in the guzzle docs in the Quickstart in section Sending Requests : 在发送请求部分的快速入门中的guzzle文档中描述了向客户端发出请求 :
$response = $guzzleClient->get('http://myhost.com/api/locales')
When the request was successful you can retrieve the locales by calling: 请求成功后,您可以通过调用以下方法检索语言环境:
$content = $response->getBody()->getContent();
Either casting getBody()
to string or using getContent()
is important here. 将
getBody()
为字符串或使用getContent()
在此处非常重要。 Again refer to Guzzle's documentation particularly the section on using responses . 再次参考Guzzle的文档,特别是关于使用响应的部分。
For example if you send a json-encoded string you can do something like: 例如,如果您发送json编码的字符串,您可以执行以下操作:
$encodedLocales = $response->getBody()->getContent();
$decodedLocales = json_decode($encodedLocales, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \Exception(json_last_error_msg());
}
There are many things that should be said about this approach such as it's fragile because it relies on a working network connection possibly to a different server, it's not easily testable, transfer exceptions are not handled gracefully, etc. pp. but for a simple proof of concept or asa starting point this should suffice. 关于这种方法应该说很多东西,比如它很脆弱,因为它依赖于可能连接到不同服务器的工作网络连接,它不容易测试,传输异常没有得到优雅处理等等。但是对于一个简单的证明概念或起点这应该足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.