0
我正在寫在線翻譯服務的包裝。目前OnlineTranslator
類看起來對我來說真的很難看,就像意大利麪代碼一樣。這是因爲可以在下劃線服務中發生許多錯誤的異常生成(Bing,實際上)。意大利麪代碼,處理異常處理和錯誤?
我不太瞭解如何處理異常和錯誤。任何改變重構我的代碼(誰說模式?)?如何擺脫代碼中的這麼多if
?
<?php
namespace DL\AdminBundle\Service;
class OnlineTranslator
{
private $_service;
private $_languages;
private $_from;
private $_to;
private $_ERRORS = array(
'UNSUPPORTED_DETECTION' => "'%s' service doesn't support language
detection. Manually call 'setFrom' to set the source language.",
'UNSUPPORTED_FROM_LANGUAGE' => "Source language code '%s' unrecognized
or not supported by this service.",
'UNSUPPORTED_TO_LANGUAGE' => "Destination language code '%s'
unrecognized or not supported by this service.",
'MISSING_TO_LANGUAGE' => "Destination language code is missing.",
'GENERIC_SERVICE_ERROR' => "'%s' service returned an error: %s."
);
function __construct(IOnlineTranslator $service)
{
// Imposta il servizio e la lingua sorgente su auto
$this->_service = $service;
$this->_from = 'auto';
$response = $this->_service->getLanguages();
if ($response->error)
throw new Exception(sprintf(
$this->_ERRORS['GENERIC_SERVICE_ERROR'],
$this->_service->getName(), $response->data));
$this->_languages = $response->data;
}
function setFrom($languageCode)
{
// Controlla se la lingua è supportata
if (!in_array($languageCode, $this->_languages))
throw new Exception(sprintf(
$this->_ERRORS['UNSUPPORTED_FROM_LANGUAGE'],
$languageCode));
// Imposta la lingua sorgente
$this->_from = $languageCode;
}
function setTo($languageCode)
{
// Controlla se la lingua è supportata
if (!in_array($languageCode, $this->_languages))
throw new Exception(sprintf(
$this->_ERRORS['UNSUPPORTED_TO_LANGUAGE'],
$languageCode));
// Imposta la lingua destinazione
$this->_to = $languageCode;
}
function translate($text)
{
// Controlla che sia impostata la lingua di destinazione
if (!isset($this->_to))
throw new Exception($this->_ERRORS['MISSING_TO_LANGUAGE']);
// Se detect è auto controlla che il servizio lo supporti
if ('auto' == $this->_from && !$this->_service->isDetectAware())
throw new Exception(sprintf(
$this->_ERRORS['UNSUPPORTED_DETECTION'],
$this->_service->getName()));
// Imposta la lingua sorgente chiamando il metodo detect
$response = $this->_service->detect($text);
if ($response->error)
throw new Exception(sprintf(
$this->_ERRORS['GENERIC_SERVICE_ERROR'],
$this->_service->getName(), $response->data));
$this->_from = $response->data;
// Traduci il testo chiamando il metodo translate
$response = $this->_service->translate($text, $this->_from,
$this->_to);
if ($response->error)
throw new Exception(sprintf(
$this->_ERRORS['GENERIC_SERVICE_ERROR'],
$this->_service->getName(), $response->data));
return $response->data;
}
}
?>
最新問題? – KingCrunch
@KingCrunch'if','if','if'和if'if'。 – gremo
'if'是否因某種原因阻止了一個問題? –