2009-04-03 2 views
0

알 수없는 이유로 알렉사 API에 질의를하는 경우가 종종 있습니다. 실패하면 최대 10 번까지 쿼리를 자동으로 다시 시도하려고합니다.PHP : 설정된 횟수만큼 또는 성공할 때까지 쿼리 재 시도

실패 할 경우 API에서 반환 한 응답에 부분 문자열 AuthFailure이 포함됩니다.

반환 할 응답이 하위 문자열 AuthFailure을 포함하지 않거나 10 번의 재시도가 시도 될 때까지 쿼리를 다시 시도 할 수있는 루프 유형은 무엇입니까?

답변

4

for 루프로이 작업을 수행 할 수 있습니다.

for($i=0; $i < 10; $i++) { 
    $return = (Alexa call here) 
    if(!strstr($return,"AuthFailure")) 
     break; 
} 

원하는대로 10을 조정하십시오. 더 나은 아직 다른 곳에서는 상수 define()을 사용하십시오. 이 횟수는 시도 횟수가 소진되거나 반환 값에 "AuthFailure"가 포함될 때까지 계속됩니다.

+0

계속 하시겠습니까? –

2

나는 같은 것을 할 것 : 나는 추가 PARAM과 전화로 그 기능을 확장 할

public function getAlexaResponse($aParam) 
{ 
    //code that does the call 
    return $response; 
} 

:

define('ALEXA_FAILED', 'AuthFailure'); 

$response = ALEXA_FAILED; 
$tries = 0; 

while ($tries <= 10 && stripos($response, ALEXA_FAILED) !== FALSE) 
{ 
    $response = GetAlexaResponse(); 
    $tries++; 
} 
0

는 개인적으로 난 함수의 예에 전화를 마무리 할 재귀 적으로 :

public function getAlexaResponse($aParam, $attempts = 10) 
{ 
    //code that does the call 
    if(!strstr($response,"AuthFailure") && ($attempt > 0)){ 
     $this->getAlexaResponse($aParam, --$attempts); 
    } 
    return $response; 
}