Challenge of one class from another
-
There's a class for work. IMAP protocol. Call him.
class1
And there's a class to work with sockets. Call him.class2
I want it.class1
Dragging methodsclass2
♪
We need all two methods.socketRequest($socketRequest)
andsocketResponse()
♪
I mean, send a request and accept an answer.
How do you do that?Figure 1: to the designer
class1
objectclass2
And then he's calling the right methods. But then it turns out the classes are tight.Figure 2: ♪
class2
implementation__invoke($socketRequest)
♪ Then I'll give you the same thing.class2
Totalclass1
but unlike the first idea, I don't pose specific methods, but the object itself uses as a function...class2($imapRequest)
♪ I mean, there's no hard connections, and then you can put everything you want.
What ideas?
-
Your task can be accomplished by one of the following types of relationships: Aggregationor Composite♪
Aggregation - When one class is to be a container of other classes. However, the duration of the classes held does not depend on the duration of the container class.
Example:
class class2 { public function socketRequest($socketRequest) { // } public function socketResponse() { // } }
class class1
{
private $foo;public function __constructor(class2 $Foo) { $this->foo = $Foo; } public function socketRequest($socketRequest) { return $this->foo->socketRequest($socketRequest); } public function socketResponse() { return $this->foo->socketResponse(); }
}
If the programme is implemented
class1
It'll be destroyed, it won't affect the class object.class2
♪Communication a stricter relationship. In contrast to the aggregation, the composite has a hard time dependence on the existence of copies of the class of the container and copies of the classes contained.
Example:
class class2
{
public function socketRequest($socketRequest)
{
//
}
public function socketResponse()
{
//
}
}class class1
{
private $foo;public function __constructor() { $this->foo = new class2; } public function socketRequest($socketRequest) { return $this->foo->socketRequest($socketRequest); } public function socketResponse() { return $this->foo->socketResponse(); }
}
If the programme is implemented
class1
will be destroyed, it will cause destruction of class objectclass2
To determine which type of relationship you need to answer the question whether class should be
class2
exist outside the clusterclass1
♪ Ifclass2
It is planned to be used elsewhere to use aggression, if not a composer.