重构了下,请多多指教 
                            
                                                    
                        
                    
                    
  
                    
                    我想知道app()实例化一个类和用new实例化,有什么区别?app()只能实例化构造函数不带参数的类吗?
<?php
namespace App\Tools;
use GuzzleHttp\Client;
use Overtrue\Pinyin\Pinyin;
class SlugTranslation
{
    private $api = 'http://api.fanyi.baidu.com/api/trans/vip/translate?';
    private $appid;
    private $key;
    private $text;
    public function __construct($text, $appid, $key)
    {
        $this->text = $text;
        $this->appid = $appid;
        $this->key = $key;
    }
    public function translate()
    {
        if(empty($this->appid) || empty($this->key)) {
            return $this->pinyin();
        }
        $http = new Client();
        $response = $http->get($this->str_query());
        $result = json_decode($response->getBody(), true);
        // 尝试获取获取翻译结果
        if (isset($result['trans_result'][0]['dst'])) {
            return str_slug($result['trans_result'][0]['dst']);
        } else {
            // 如果百度翻译没有结果,使用拼音作为后备计划。
            return $this->pinyin();
        }
    }
    private function pinyin()
    {
        return str_slug(app(Pinyin::class)->permalink($this->text));
    }
    private function str_query()
    {
        $salt = time();
        $sign = md5($this->appid. $this->text . $salt . $this->key);
        // 构建请求参数
        $query = http_build_query([
            "q"     =>  $this->text,
            "from"  => "zh",
            "to"    => "en",
            "appid" => $this->appid,
            "salt"  => $salt,
            "sign"  => $sign,
        ]);
        return $this->api.$query;
    }
}
 
           
         
             
             
             
             
             
             
             
             
             
             
             
             
             
                     
                     
             
             
         
             
             
         
           
           关于 LearnKu
                关于 LearnKu
               
                     
                     
                     粤公网安备 44030502004330号
 粤公网安备 44030502004330号 
 
推荐文章: