如何使用Request :: factory() - > execute()从同一主机中的另一个库调用脚本

时间:2013-02-15 23:42:04

标签: php request kohana kohana-3.2

我正在使用Kohana 3.2,我希望能够调用另一个脚本(与其管辖区之外的Kohana无关)返回application/json响应。 当我尝试使用时:

$response = json_decode(Request::factory('/scripts/index.php?id=json')->execute()->body());

错误地说没有scripts/index.php的路线。所以我尝试使用Request_Client_External

Request_Client_External::factory()->execute(Request::factory('/scripts/index.php?page=s'))->body();

给我Request_Exception [ 0 ]: Error fetching remote /scripts/index.php?page=s [ status 0 ] Could not resolve host: scripts; Host not found。它似乎需要使用http / https的完整标记的URL,但如何避免它执行真正的外部请求的开销?

做一个

Request::factory(url::site('/scripts/index.php?page=s', 'http'))->execute()

有效但被认为是“外部”吗?

1 个答案:

答案 0 :(得分:1)

对你的问题的简短回答是,使用Request::factory()->execute()实现这一目标的唯一方法是使用传递给它的完整URL(带有任何“开销”,这不应该太多:你的服务器可能很擅长与自己说话。)

否则,理想情况下,您将scripts的功能放入库中并从Kohana调用它。然而,听起来这不适合你。如果您必须在“内部”请求中保持/scripts/index.php不变且坚持,则可以使用PHP's output buffering,如下所示。但是有一些警告,所以我不推荐它:最好的方法是传递一个完整的URL。

    // Go one level deeper into output buffering
    ob_start();

    // Mimic your query string ?id=json (see first caveat below)
    $_GET = $_REQUEST = array('id' => 'json');
    // Get rid of $_POST and $_FILES
    $_POST = $_FILES = array();

    // Read the file's contents as $json
    include('/scripts/index.php');
    $json = ob_get_clean();

    $response = json_decode($json);

一些警告。

首先,代码更改$_GLOBALS。您可能不会在Kohana代码中使用这些(您使用$this->request->get()就像一个好的HMVCer,对吧?)。但是如果你这样做,你应该'记住'然后恢复这些值,将$old_globals = $GLOBALS;等放在上面的代码之前,然后放在$GLOBALS = $old_globals;之后。

会话:如果你的/scripts/index.php使用`session_start(),如果你已经在Kohana这个时候开始了一个会话,这将会引发警告。

请注意,scripts/index.php中设置的所有变量都将保留在您所处的上下文中。如果您想避免与该上下文发生冲突,您可以启动一个新的上下文,即将上面的内容包含在其中自己的功能。

最后,您还需要确保/scripts/index.php不执行Kohana::base_url = 'something_else'之类的操作,或触摸任何其他静态属性,或执行灾难性using this

相关问题