JohanM Posted March 31, 2020 Share Posted March 31, 2020 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 Quote Link to comment Share on other sites More sharing options...
gw1500se Posted March 31, 2020 Share Posted March 31, 2020 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.