S
S
ssrdop2018-02-04 21:41:11
OOP
ssrdop, 2018-02-04 21:41:11

How to control the object type being created in a method of another class?

For example, we have a Maker class

Class MyClass
{
 
 public function __construct(SomeClass $obj, AnotherClass $obj2)
 {
   // инициализация с переданными параметрами
 }
 private function doSomething()
  {
     $event = new ConcreteEvent();
    // И дальше что то делаем
  }

}

The question is in the doSomething method. In it, I create an object of the concreteEvent class and then some code. But what if I need to create an object of the OtherEvent class in the doSomething() method of the MyClass class.
Pass a factory to the constructor? But then the signature of the constructor will be inflated. And if there are 10 such methods?
Inherit the class MyClass, in order to rewrite only one method. And if you need variations with other similar methods?
It is important to note that such methods are either private or protected. That if from the outside it is impossible to transfer parameters to them.
What is the more logical thing to do?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2018-02-04
@ssrdop

Pattern Strategy
We make a common interface for Event objects (I came up with the begin() method out of my head):

interface EventInterface
{
        public function begin();
}

and create different events:
class ConcreteEvent implements EventInterface
{
        public function begin()
        {
                // ..
        }
}
class OtherEvent implements EventInterface
{
        public function begin()
        {
                // ..
        }
}

In our MyClass we create an $event property and a setter for it and use it:
Class MyClass
{
        private $event;

        public function __construct(SomeClass $obj, AnotherClass $obj2)
        {
                // инициализация с переданными параметрами
        }
        
        public function setEvent(EventInterface $event)
        {
                $this->event = $event;
        }

        private function doSomething()
        {
                // Работаем с нашим event
                $someDoing = $this->event->begin();
        }
}

Then already in the final code we will need to work like this:
$myObj = new MyClass(SomeClass $obj, AnotherClass $obj2);

// Set Event
$myObj->setEvent(new OtherEvent);

// Далее работаем с наши готовым объектом, у которого уже есть нужны Event

I SORRY IN ADVANCE IF I AM MISTAKEN - I myself have been studying patterns for 3 days.
Perhaps the application further on the implementation is not suitable for you - you need to look at what and how
For some reason I thought that such a question would gain popularity

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question