Jump to content

Wrapping external class


Recommended Posts

Hi guys! I have a specific requirement and need some help

Say i have an external api library with Client class looking like this:

class Client 
{ 

  some constants.. 
  private props.., 

  __construct() 

  public static function create($url) 
  { 
      some code 
  } 

  public static function authenticate($token) 
  { 
      some code 
  } 

  ...dozen other methods 
}

Current way of instantiating in every single other class where i need the client:

use Client; 

MyFetchController 
{ 
	private $client; 
	
	public function __construct() 
	{ 
		$this->client = Client::create(getenv('URL'))->authenticate(getenv('TOKEN')) 
	} 

	$this->client->use other methods in Client class 
}

Is there a way to wrap that class so i have external parameters loaded through .env file automaticaly available on new wrapper class intialization with something like this:

MyFetchController 
{ 
	private $client; 

	public function __construct(WrappedClient $client) 
	{ 
		$this->client = $client 
	} 

	public function getData() 
	{ 
		$data = $this->client->parse(...) 
	} 
}

Basically what i need is a class ready for DI in all other classes without inserting required auth and other parameters in constructor every single time

Link to post
Share on other sites

I think you are asking for a singleton class:

class MyFetchController {
   $inst=null;
// private constructor so it cannot be instantiated externally
   private function__contruct() {
      // initialzation code here as needed
   }
   public function Instance() {
      if ($inst==null) {
         $inst=new MyFetchController();
      }
      return $inst;
   }
}

Any time you want that class call 'Instance' and you will always get the same instance.

Link to post
Share on other sites
This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.