One way is to use the concept of composition. If your WebService requires a user to use the API, you can do something like:
class Usuario {...}
class WebService {
private $user;
public function __construct(Usuario $user) {
$this->user = $user;
}
}
And use, in WebService
, $this->user
to access the user in question. The WebService instance would look something like this:
$webService = new WebService(new Usuario());
Interface Note
To get even more concise with OOP concepts, instead of setting the WebService
parameter to the Usuario
class, you can create an interface:
interface UsuarioInterface
{
public function getUsername();
public function setUsername($username);
public function getPassword();
public function setPasswrod($passwrod);
}
And in class WebService
:
class WebService {
private $user;
public function __construct(UsuarioInterface $user) {
$this->user = $user;
}
}
What does it change? In the first solution the constructor parameter must necessarily be an instance of Usuario
(of the class itself or any other that extends the class), but depending on the size of your application, this limitation may be a problem. In the second solution, any class that implements the UsuarioInterface
interface can serve as a parameter. This practice is very useful when integrating your application with third-party codes (if applicable).