工厂抽象模式特点是对象组合、簇产品解耦,所以采用工厂抽象来封装三种翻译接口
导语
小牛翻译和百度翻译需要申请账号后才能使用,免费的基本能满足使用需求,申请方式也非常简单。
百度翻译申请:https://api.fanyi.baidu.com/product/11
小牛翻译申请:https://niutrans.com/documents/develop/develop_text/free#accessMode
调用案例
可以看到下面的例子在实例化Translatectory
这个类后,就可以直接使用各种翻译。
Translatectory下载链接:https://gitee.com/PHPchengxuyuan/php-translates.git
注意:下载后请放入自己的项目中,另外记得修改Translatectory包中的所有文件的命名空间
调用翻译例子:
$model = new IndexController();
echo $model->actionIndex('我被翻译了,咿呀咿呀哟!');
//输出 “I have been translated, Eyah Eyah!”
<?php
use app\translates\Translatectory;
class IndexController
{
function actionIndex($text = '') {
//启动工厂
$model = new Translatectory();
//小牛翻译、百度翻译通过构造方法传递账号
$basic = [
'apikey' => 'xxxx', //小牛翻译apikey
// 'appid' => 'xxx', //百度翻译appid
// 'key' => 'xxx',//百度翻译key
];
//获得小牛翻译具体
$form = $model->NiuTranslate($basic);
//百度翻译
// $form = $model->BaiduTranslate($basic);
//谷歌翻译1
// $form = $model->GoogleTranslate();
//谷歌翻译2
// $form = $model->Google2Translate();
$form->target = "en"; //目标语言en-英语,其他语言编号按照国际通用编号,具体不同翻译可能会有差异,请在各自的官网进行查询,
$form->source = "zh"; //源语言 zh-中文,其他语言编号按照国际通用编号,具体不同翻译可能会有差异,请在各自的官网进行查询
$form->text = $text;
//生产
$form->translate();
//输出翻译
return $form->run();
}
}