2014-09-21 93 views
1

我有一些耗時的代碼來處理一系列希望運行的HTTP請求的結果的背景。我正在使用Redis存儲管理隊列。以下是我已經試過:有沒有辦法將回調作爲數據參數傳遞給Laravel 4.2隊列:: push()

Queue::push('FetchUrls', [ 
    'urls'  => [ 'http://one.com', 'http://two.com', 'http://three.com' ], 
    'complete' => function($response) { /* process data returned by URL here */ }, 
    'error' => function($error ) { /* process HTTP errors here */ }, 
]); 

什麼Redis的隊列存儲顯示出來是JSON系列化$data參數:

{ 
    "job": "FetchUrls", 
    "data": { 
     "urls": [ 
      "http:\/\/one.com", 
      "http:\/\/two.com", 
      "http:\/\/three.com" 
     ], 
     "complete": [], 
     "error": [] 
    }, 
    "id": "aAlkNM0ySLXcczlLYho19TlWYs9hStzl", 
    "attempts": 1 
} 

正如你所看到的,回調只是顯示爲空隊列存儲中的數組。我以前從未使用Queue類,所以我可能以錯誤的方式處理這個問題。我正在尋找一個解決此問題的最佳方法的建議。謝謝!

回答

2

您可以傳遞函數名稱並用類似call_user_func()的方法調用它們。

Queue::push('FetchUrls', [ 
    'urls'  => ['http://one.com', 'http://two.com', 'http://three.com'], 
    'complete' => ['ResponseHandler', 'fetchComplete'], 
    'error' => ['ResponseHandler', 'fetchError'], 
]); 

class FetchUrls 
{ 
    public function fire($job, $data) 
    { 
     list($urls, $complete, $error) = $data; 

     foreach ($urls as $url) { 
      if ($response = $this->fetch($url)) { 
       $job->delete(); 
       call_user_func($complete, $response); 
      } else { 
       $job->release(); 
       call_user_func($error, $this->getError()); 
      } 
     } 
    } 

    private function fetch($url) 
    { 
     // ... 
    } 

    private function getError() 
    { 
     // ... 
    } 
} 

class ResponseHandler 
{ 
    public static function fetchComplete($response) 
    { 
     // ... 
    } 

    public static function fetchError($error) 
    { 
     // ... 
    } 
} 

這種方法有一個不是基於類的版本,但這是相對乾淨的。

call_user_func()['ResponseHandler', 'fetchComplete']作爲第一個參數將調用ResponseHandler::fetchComplete()

+0

謝謝!這是我正在尋找的解決方案! – morphatic 2014-09-22 05:56:21

3

爲了安全起見,您應該只推送數組(因爲序列化問題)。
要回答你的問題 - 沒有解決方法,你應該重新思考邏輯。

相關問題