Best way to apply the concept of object orientation

2

I have a class Usuario

class Usuario{

}

Let's say that user needs to access some different Web Services for features and information. I then thought about creating a class called WebService and grouping all methods with API access and external services there.

class WebService {

}

My question is. The user is not a WebService , so I can not and should not extend this class. Thus. What is the best way to use it in Usuário ? I must create your methods as abstract and simply use them. Or is there a better approach to this case?

    
asked by anonymous 06.04.2017 / 16:18

1 answer

4

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).

    
06.04.2017 / 17:12