Miguel Stevens
Miguel Stevens

Reputation: 9220

Passing the results of an API call to the class

I've made my own Wrapper for an API I'm working with, Now I have a class where uses can register and I need to results of that API call in the whole class.

So I'm wondering if it's possible to have the result object that the API returns as an object to work with and pass to other methods

Here's my code, I added inline comments to clarify the issue

class RegisterController extends Controller {

    private $company;

    public function __construct()
    {
        // This is not the object I want, It's the class that communicates with the API
        $this->company = new Teamleader\Company;
    }

    public function index($id = null)
    {
        // I'm trying to set the class to the result of the API call ( returns an StdObject )
        $this->company = $this->company->get($id);

        // Still returns the original object, not the result of the API call
        var_dump($this->company);
    }

    public function register()
    {
        // Also returns the original object
        dd($this->company);
    }

}

Thank you very much, a confused developer.

Upvotes: 0

Views: 91

Answers (1)

user1669496
user1669496

Reputation: 33108

Instead of trying to overwrite the api wrapper, just set it as some custom response object.

namespace Teamleader;

class CompanyResponse {

    protected $data = null;

    public function __construct(\stdClass $data)
    {
        $this->data = $data;
    }

    // Whatever other methods you want to be in the API response
}

And then in the get method in Teamleader\Company you will return new CompanyResponse($data)

In the index method in RegisterController, set the response object as a different class property. There really isn't much of a reason to overwrite the API wrapper you created.

$this->companyResponse = $this->company->get($id);

Upvotes: 1

Related Questions