'Implement an interface in a class with additional methods
I'm trying to embrace clean code and design patterns and came across to the following scenario.
My interface
interface SystemLogInterface
{
public function log(string $type);
}
And my class implementation
class LogDownloadService implements SystemLogInterface
{
public function log(string $type)){}
}
I have another logging class, similar to the one above.
class LogUserService
{
public function setAttr(){}
public function log(string $type)){}
}
Because this class has an extra method setAttr() it does not implement same interface.
For example, let's suppose that my LogUserService class was implementing SystemLogInterface
public function foo(LogUserService $service)
{
$service->setAttr($this->getAttr())
$service->log()
}
If I want to change the injected service to another implementation, i would have to change the body of the method foo(), because the setAttr() method will not exist.
I want to achieve, if possible, a result to have both classes implementing the same interface or another solution.
Note: setAttr() can not be moved to the constructor
Solution 1:[1]
I think you are misunderstanding the point of interfaces.
An interface, in effect, defines the contract between classes. This has two perspectives for classes:
in class, that implements an interface, it indicates what capabilities the has. And each class can implement multiple interfaces, some of which will be unrelated and some of which will overlap.
in class, that requires an interface, it indicates which specific capabilities the following code will need from a given object.
So ... how I would approach this.
You need to create another interface, that contains your setAttr method (let's call it: WithAttributes). Then you need to create an interface, that inherits SystemLogInterface and WithAttribures.
This "composite interface" would be the one that your LogUserService actually implements. And you would be able to then pass the instance of it both to the methods, that require the new;y created composite AND the old code requiring the SystemLogInterface functionality.
P.S. why do you call your interface SystemLogInterface but not your class LogUserServiceClass .... you really should be more consistent :P
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tereško |
