重构了下,请多多指教

我想知道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;
    }

}
本帖已被设为精华帖!
本帖由系统于 4年前 自动加精
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 9

看了楼主的代码,有了灵感,所以我也试着重构了一下这部分的代码,想要实现了一个简单的百度翻译接口。
新手的牛刀小试,请多多指教。

<?php
namespace App\Handlers;

use GuzzleHttp\Client;
use Overtrue\Pinyin\Pinyin;


class BaiduTranslate
{
    // 初始化配置信息
    private $api;
    private $appid;
    private $key;

    // 配置翻译方式
    private $from;
    private $to;

    public function __construct($from = 'zh', $to = 'en')
    {
        // 我觉得这部分的属性赋值可以直接用全局变量数组$_ENV代替
        // 应该看看数据库连接的源码找找灵感
        // 这里就先这样写着,作为新手逻辑清晰点
        $this->appid = $_ENV['BAIDU_TRANSLATE_APPID'];
        $this->key = $_ENV['BAIDU_TRANSLATE_KEY'];
        $this->api = $_ENV['BAIDU_TRANSLATE_API_URL'];
        $this->from = $from;
        $this->to = $to;
    }

    public function translate($text)
    {
        // 如果没有配置百度翻译,自动使用兼容的拼音方案
        // 按照个需,这里应该要有报错信息,API 配置不全
        if (empty($this->appid) || empty($this->key)){
            return app(Pinyin::class)->permalink($text);
        }

        // 实例化 HTTP 客户端
        $http = new Client;

        // 发送 HTTP GET 请求
        $response = $http->get($this->query($text));

        // decode 返回的 response body 内的数据
        $result = json_decode($response->getBody(), true);

        if (isset($result['trans_result'][0]['dst'])){
            return $result['trans_result'][0]['dst'];
        }else{
            // 如果百度翻译没有结果,使用拼音作为后备计划
            // 照思路这里应该返回报错,翻译 API 接入有问题
            return app(Pinyin::class)->permalink($text);
        }
    }

    // 创建请求语句
    private function query($text)
    {
        //根据百度翻译API文档,生成 sign
        //http://api.fanyi.baidu.com/api/trans/product/apidoc
        //appid+q+salt+密钥 的MD5值
        $salt = time();
        $sign = md5($this->appid . $text . $salt . $this->key);

        //构建请求参数
        $query = http_build_query([
            'q' => $text,
            'from' => $this->from,
            'to' => $this->to,
            'appid' => $this->appid,
            'salt' => $salt,
            'sign' => $sign,
        ]);

        return $this->api . $query;
    }
}
5年前 评论

既然重构,就来一下啊

<?php
namespace App\Handlers;

use GuzzleHttp\Client;
use Illuminate\Support\Str;
use Overtrue\Pinyin\Pinyin;

class SlugTranslator
{

    protected $api = 'http://api.fanyi.baidu.com/api/trans/vip/translate?';
    protected $appid;
    protected $secret;
    protected $from = 'zh';
    protected $to = 'en';

    /**
     * SlugTranslator constructor.
     */
    public function __construct()
    {
        $this->appid = config('services.baidu_translate.appid');
        $this->secret = config('services.baidu_translate.secret');
    }

    /**
     * Get slug
     *
     * @param $text
     *
     * @return string
     */
    public function translate($text)
    {
        $slug = $this->baidu($text) ?: $this->pinyin($text);
        return $slug;
    }

    /**
     * Get slug with Baidu Translate service.
     *
     * @param $text
     *
     * @return bool|string
     */
    public function baidu($text)
    {

        if (empty($this->appid) || empty($this->secret)) {
            return false;
        }

        $salt = time();
        $sign = md5($this->appid . $text . $salt . $this->secret);

        $query = http_build_query([
            'q' => $text,
            'from' => $this->from,
            'to' => $this->to,
            'appid' => $this->appid,
            'salt' => $salt,
            'sign' => $sign,
        ]);

        $http = new Client();
        $response = $http->get($this->api . $query);
        $result = json_decode($response->getBody(), true);

        if (isset($result['trans_result'][0]['dst'])) {
            return Str::slug($result['trans_result'][0]['dst']);
        }

        return false;
    }

    /**
     * Get slug with pinyin.
     *
     * @param $text
     *
     * @return string
     */
    public function pinyin($text)
    {
        return Str::slug(app(Pinyin::class)->permalink($text));
    }
}
4年前 评论

看了楼主的代码,有了灵感,所以我也试着重构了一下这部分的代码,想要实现了一个简单的百度翻译接口。
新手的牛刀小试,请多多指教。

<?php
namespace App\Handlers;

use GuzzleHttp\Client;
use Overtrue\Pinyin\Pinyin;


class BaiduTranslate
{
    // 初始化配置信息
    private $api;
    private $appid;
    private $key;

    // 配置翻译方式
    private $from;
    private $to;

    public function __construct($from = 'zh', $to = 'en')
    {
        // 我觉得这部分的属性赋值可以直接用全局变量数组$_ENV代替
        // 应该看看数据库连接的源码找找灵感
        // 这里就先这样写着,作为新手逻辑清晰点
        $this->appid = $_ENV['BAIDU_TRANSLATE_APPID'];
        $this->key = $_ENV['BAIDU_TRANSLATE_KEY'];
        $this->api = $_ENV['BAIDU_TRANSLATE_API_URL'];
        $this->from = $from;
        $this->to = $to;
    }

    public function translate($text)
    {
        // 如果没有配置百度翻译,自动使用兼容的拼音方案
        // 按照个需,这里应该要有报错信息,API 配置不全
        if (empty($this->appid) || empty($this->key)){
            return app(Pinyin::class)->permalink($text);
        }

        // 实例化 HTTP 客户端
        $http = new Client;

        // 发送 HTTP GET 请求
        $response = $http->get($this->query($text));

        // decode 返回的 response body 内的数据
        $result = json_decode($response->getBody(), true);

        if (isset($result['trans_result'][0]['dst'])){
            return $result['trans_result'][0]['dst'];
        }else{
            // 如果百度翻译没有结果,使用拼音作为后备计划
            // 照思路这里应该返回报错,翻译 API 接入有问题
            return app(Pinyin::class)->permalink($text);
        }
    }

    // 创建请求语句
    private function query($text)
    {
        //根据百度翻译API文档,生成 sign
        //http://api.fanyi.baidu.com/api/trans/product/apidoc
        //appid+q+salt+密钥 的MD5值
        $salt = time();
        $sign = md5($this->appid . $text . $salt . $this->key);

        //构建请求参数
        $query = http_build_query([
            'q' => $text,
            'from' => $this->from,
            'to' => $this->to,
            'appid' => $this->appid,
            'salt' => $salt,
            'sign' => $sign,
        ]);

        return $this->api . $query;
    }
}
5年前 评论

既然重构,就来一下啊

<?php
namespace App\Handlers;

use GuzzleHttp\Client;
use Illuminate\Support\Str;
use Overtrue\Pinyin\Pinyin;

class SlugTranslator
{

    protected $api = 'http://api.fanyi.baidu.com/api/trans/vip/translate?';
    protected $appid;
    protected $secret;
    protected $from = 'zh';
    protected $to = 'en';

    /**
     * SlugTranslator constructor.
     */
    public function __construct()
    {
        $this->appid = config('services.baidu_translate.appid');
        $this->secret = config('services.baidu_translate.secret');
    }

    /**
     * Get slug
     *
     * @param $text
     *
     * @return string
     */
    public function translate($text)
    {
        $slug = $this->baidu($text) ?: $this->pinyin($text);
        return $slug;
    }

    /**
     * Get slug with Baidu Translate service.
     *
     * @param $text
     *
     * @return bool|string
     */
    public function baidu($text)
    {

        if (empty($this->appid) || empty($this->secret)) {
            return false;
        }

        $salt = time();
        $sign = md5($this->appid . $text . $salt . $this->secret);

        $query = http_build_query([
            'q' => $text,
            'from' => $this->from,
            'to' => $this->to,
            'appid' => $this->appid,
            'salt' => $salt,
            'sign' => $sign,
        ]);

        $http = new Client();
        $response = $http->get($this->api . $query);
        $result = json_decode($response->getBody(), true);

        if (isset($result['trans_result'][0]['dst'])) {
            return Str::slug($result['trans_result'][0]['dst']);
        }

        return false;
    }

    /**
     * Get slug with pinyin.
     *
     * @param $text
     *
     * @return string
     */
    public function pinyin($text)
    {
        return Str::slug(app(Pinyin::class)->permalink($text));
    }
}
4年前 评论

@KKKKUNG 调用次数一多,会被百度屏蔽?

5年前 评论

@phpero 我觉得应该不会吧。就好比你用百度翻译,你用得多就会把你屏蔽了吗?即使真的要屏蔽,那也应该要在短时间内达到一个对他服务器造成威胁的访问量吧。再或者是需要你充波钱,开个会员之类的。具体的看百度给的文档呀。

5年前 评论

@phpero 你是用的我这个这个类吗?api,key,appid 你先确定都写在env文件里了,然后 translate 方法返回的是翻译之后的原字符串,写入数据库的那个数据应该是把字符串内容中的空格用‘-’替换掉的数据,这样的数据在URL里是合格的。

5年前 评论

超级棒,面相对象编程。

5年前 评论
UKNOW 4年前

@phpero 不会被屏蔽 有收费标准的 调的多了就得付费了

若当月翻译字符数≤2百万,当月免费;若超过2百万字符,按照49元/百万字符支付当月全部翻译字符数费用

5年前 评论
任飘渺

@phpero 过多的话会被屏蔽一会的,就像邮箱接口一样,但是翻译字数是计费的

5年前 评论

我想知道app()实例化一个类和用new实例化,有什么区别?app()只能实例化构造函数不带参数的类吗?是的,app是去容器内拿数据,如果构造函数有参数。这时候无论是app()还是依赖注入的方式,都不能。只能使用传统的new一个实例

5年前 评论
arkssss 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!