One way is to use the compositional concept. 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 be something like:
$webService = new WebService(new Usuario());
Note on interfaces
To be even more concise with the concepts of OOP, instead of defining the parameter of WebService
as being of the class Usuario
, 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 this change? In the first solution the constructor parameter must be an instance of Usuario
(of the class itself or any other that extends the class), but depending on the size of its application, this limitation may be a problem. In the second solution, any class that implements the interface UsuarioInterface
can serve as a parameter. This practice is quite useful when integrating your application with third party codes (if applicable).
$webservice = new WebService()
?– Caio Felipe Pereira
@Caiofelipepereira this is my doubt. If I should treat like this, using abstract methods, or if there is some other better approach.
– alan