2012-02-05 69 views
0

我有腳本生成一些圖形,並返回結果,也是它緩存此圖形等Symfony - 如何執行另一個PHP腳本並獲得結果?

我使用Symfony2中,並在控制器我需要調用這個腳本,現在我用這個功能,調用我的PHP腳本:

 private function http_post($url, $data) 
      { 
       $data_url = http_build_query ($data); 
       $data_len = strlen ($data_url); 

       return array ('content'=>file_get_contents ($url, false, stream_context_create (array ('http'=>array ('method'=>'POST' 
         , 'header'=>"Connection: close\r\nContent-Length: $data_len\r\nContent-Type: application/x-www-form-urlencoded\r\n" 
         , 'content'=>$data_url 
         )))) 
        , 'headers'=>$http_response_header 
        ); 
      } 

我認爲這種方式不是最好的,我記得很好file_get_contents是相當緩慢? 所以我的問題:通過「http_post」向POST腳本發送POST是否好方法?如果沒有,比什麼更好?

編輯:我不想在控制器中有這個腳本,所以請不要包含解決方案:)。

+0

是產生的symfony應用程序的圖形部分或者是一個單獨的腳本浮動腳本在某個地方? – F21 2012-02-05 00:26:59

+0

個人腳本在同一臺服務器上。 – 2012-02-05 00:46:26

回答

2

如果您希望將圖像生成器作爲控制器實現,您只需返回正常的響應:return new Response($generated_image);

所以這可能是你的控制器:

namespace Acme\MyBundle\Controller; 
use Symfony\Component\HttpFoundation\Response; 

class ImageGeneratorController 
{ 
    public function generateAction($parameters) 
    { 
     //Generate an image using parameters and store it in $image 
     $image = .... 

     return new Response($image); 
    } 
} 

然後,您可以call your image generator from any controller使用forward()

public function indexActionInAnotherController($name) 
{ 
    $response = $this->forward('AcmeMyBundle:ImageGenerator:generate', array(
     'name' => $name, 
     'color' => 'green' 
    )); 

    // further modify the response or return it directly 

    return $response; 
} 
+0

是的,經過我的考慮和你的代碼,我認爲這將是最好的解決方案。我有一個問題,將imagepng()替換爲Response對象,但我找到了這個解決方案:http://stackoverflow.com/questions/7365622/convert-image-to-string-for-symfony2-response – 2012-02-05 01:36:34

2

你在做什麼沒有問題,但是如果你想探索一個替代方案,很多人都會使用curl庫,它是快速和健壯的。

+0

+1。如果這個腳本不是你的應用程序的一部分,除了使用'include()'外,這是你可以做的最好的事情,這會變得混亂。 – F21 2012-02-05 01:05:54

+0

實際上,我已經用捲曲對它進行了測試,而對於我的情況,我感到驚訝的是它的工作速度慢了兩倍,但我不確定調試模式或本地主機上的服務器是否可以導致它。我在另一個腳本中使用curl,它的工作速度比file_get_contents – 2012-02-05 01:08:29

+0

快很多,我沒有看到發生捲曲。由於它的編譯速度通常非常快。 – gview 2012-02-05 02:03:43

相關問題