Mr Rost Mr Rost - 1 month ago 8
PHP Question

Avoid object instantiation in method

What is the best way to have one instance of some object in class? I'm using yii2-httpclient and use Client class. I have different methods thank make requests for differents web API but I think its bad idea to creating new object when calling method. I'm trying make instance in constructor but have error

"Call to a member function createRequest() on a non-object"
. How can I do this another way?

My Controller:

<?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);
}
}

Answer

You can something like this:

class ExchangeRates extends Model
{
    public $client;

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

Now you can use it like this:

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