简体   繁体   English

尝试在使用用户冻结时将php嵌入我的树枝文件中

[英]Trying to embed php within my twig files whilst using userfrosting

I need to include some form of API call within my userfrosting site, however I am finding it difficult to find a way to do this. 我需要在userfrosting网站中包含某种形式的API调用,但是我发现很难找到一种方法来做到这一点。 I have seen that one of the ways to add PHP to twig files is by creating an extension, but this does not seem to be what I'm looking for exactly. 我已经看到将PHP添加到树枝文件的一种方法是创建一个扩展,但这似乎并不是我要寻找的。

I need to be able to pull data using a third party API which I have previously been using PHP to make calls with, however if any of you think I should use a different method to do this I am open to suggestions 我需要能够使用以前使用PHP进行调用的第三方API来提取数据,但是如果您认为我应该使用其他方法来做到这一点,我欢迎您提出建议。

TIA TIA

For Userfrosting >4.1, in your sprinkle/composer.json file, add a requirement to include Guzzle: "require": {"guzzlehttp/guzzle": "~6.0"} 对于> 4.1的Userfrosting,在您的drop / composer.json文件中,添加一个要求以包含Guzzle: "require": {"guzzlehttp/guzzle": "~6.0"}

(remember to run composer update to install the new dependency. (请记住运行composer update以安装新的依赖项。

Guzzle Docs 食尸鬼文档

Then in your controller include guzzle: 然后在您的控制器中加入食尸鬼:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ConnectException;

then you can initiate guzzle with: 那么您可以使用以下方法来启动食尸鬼:

$client = new Client([
    'base_uri' => $config['api']['host'].'/',
    'timeout' => 5 // your timeout param
]);

(I set my api host in the sprinkle config, using an environment variable, so its not hardcoded.) (我使用环境变量在sprinkle配置中设置了api主机,因此未对其进行硬编码。)

you can then make a POST request as follows, returning the response into a variable. 然后,您可以按以下方式发出POST请求,将响应返回到变量中。

$api_response = $client->post('your_api_route', [
    'json' => [
        'api_param_1' => 'Hello',
        'api_param_2' => 'World!'
    ]
]);

Also reccomended the wrap the last bit in a try and catch an guzzle/http exceptions. 还建议在try捕获guzzle / http异常后换行。

If your response is a JSON document, you can retrieve the contents into an array with: 如果您的响应是JSON文档,则可以使用以下方法将内容检索到数组中:

$data = json_decode($api_response->getBody()->getContents(), true);

I talk to an API in my userfrosting setup within the controller called by my route, then pass that data to my template. 我在我的路由调用的控制器内的用户霜设置中与API通讯,然后将该数据传递给模板。 Check out the first tutorial on how to create a new template and pass data to it. 查看有关如何创建新模板并将数据传递给它的第一个教程 Do whatever with PHP that you need to within the route (via a controller). 使用路由(需要通过控制器)对PHP进行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM