0

I'm just going to show what I mean, and I want to know whether it is good coding practices or should I try to avoid it?

class Connector { public function __constructer ($ip, $port) { $this->socket = fsockopen($ip, $port); // Forgive me, this is simply just example, never going to be used in real-life return $this->socket; } public function getInfo() { // return information which maybe properties of the server the ip is connected too } } // I just want the class Connector to handle the connection, and keep it running // Query will be used for use of the application itself and I don't want to extend connector class Query { protected $connection; public function connect ($ip, $port) { $this->connection = new Connector($ip, $port); } public function showInfo() { return echo $this->connection->getInfo(); } } 

Please do understand, this code is not for any kind of use, it's just a small example of something more logical which I'm not posting here.

1 Answer 1

2

Yes it is a good practice but you can make it more flexible:

class Query { protected $connection; public function connect (Connector $connector) { $this->connection = $connector } public function showInfo() { return $this->connection->getInfo(); } } 

This is what we call Dependency Injection.

and even more flexible would be using an interface:

interface ConnectorInterface { public function __construct(array $options); public function showInfo(); } 

and then create one or more classes that implements the interface:

class Connector implements ConnectorInterface { private $ip; private $port; public function __construct(array $options) { $this->ip = $options['ip']; $this->port = $options['port']; } public function getInfo() { return 'basic connector'; } } class AdvancedConnector implements ConnectorInterface { private $ip; private $port; private $protocol; public function __construct(array $options) { $this->ip = $options['ip']; $this->port = $options['port']; $this->protocol = $options['protocol']; } public function getInfo() { return 'advanced connector'; } } 

and then accept any class that implements ConnectorInterface into the Query::connect method:

class Query { protected $connection; // changed the parameter to ConnectorInterface !!! public function connect (ConnectorInterface $connector) { $this->connection = $connector } public function showInfo() { return echo $this->connection->getInfo(); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

In other words, no, it's not great practice. Use dependency injection and/or Interfaces where possible.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.