避免在方法中进行对象实例化

时间:2016-11-01 12:29:37

标签: php yii2

在课堂上拥有某个对象的一个​​实例的最佳方法是什么?我正在使用yii2-httpclient并使用Client类。我有不同的方法感谢不同的web API请求,但我认为在调用方法时创建新对象是个坏主意。我正在构造函数中尝试make实例但是有错误"Call to a member function createRequest() on a non-object"。我怎么能这样做呢?

我的控制器:

<?php
namespace app\models;

use yii;
use yii\base\Model;
use yii\httpclient\Client;

class ExchangeRates extends Model
{

    function __construct()
    {
        $client = new Client();
    }
    public function getPrivatRate()
    {
        // $client = new Client();
        $privatResponse = $client->createRequest()
        ->setMethod('get')
        ->setUrl('https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5')
        ->send();
        return json_decode($privatResponse->content, true);
    }
    public function getNationalRate()
    {
        // $client = new Client();
        $nbuResponse = $client->createRequest()
        ->setMethod('get')
        ->setUrl('https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?valcode=USD&date=20161101&json')
        ->send();
        return json_decode($nbuResponse->content, true);
    }
    public function getMejBankRate()
    {
        // $client = new Client();
        $mejResponse = $client->createRequest()
        ->setMethod('get')
        ->setUrl('http://api.cashex.com.ua/api/v1/exchange/mejbank')
        ->send();
        return json_decode($mejResponse->content, true);
    }
    public function getBlackMarketRate()
    {
        // $client = new Client();
        $blackMarketResponse = $client->createRequest()
        ->setMethod('get')
        ->setUrl('http://api.cashex.com.ua/api/v1/exchange/black-market')
        ->send();
        return json_decode($blackMarketResponse->content, true);
    }
}

1 个答案:

答案 0 :(得分:0)

你可以这样:

class ExchangeRates extends Model
{
    public $client;

    public function init()
    {
        parent::init();
        $this->client = new Client();
    }

现在您可以像这样使用它:

$privatResponse = $this->client->createRequest()->...