Best way to apply the concept of Object Orientation

Asked

Viewed 63 times

2

I own a class Usuario

class Usuario{

}

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

class WebService {

}

My question is. The user is not a WebService, so I cannot and should not extend this class. So. 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?

  • $webservice = new WebService() ?

  • @Caiofelipepereira this is my doubt. If I should treat like this, using abstract methods, or if there is some other better approach.

1 answer

4


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

  • Excellent @Anderson. It was something like this I was looking for.

  • I find it strange that a webservice receives a user. Perhaps the opposite would be better, because whoever uses something should receive something to use.

  • @Piovezan does not necessarily. The logic that must be analyzed is who is composed of what. A user is not composed of a Webservice, but this has in its composition a user to perform the authentication.

  • Oh yes, you’re right. Had no user related to authentication.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.