M
M
Metalbrother2014-05-14 13:51:31
PHP
Metalbrother, 2014-05-14 13:51:31

What is the best way to implement setting the execution order of methods?

There are classes ModuleA, ModuleB, ModuleC, ... . Each with its own set of methods:

abstract class AbstractModule { /* ... */ }

class ModuleA extends AbstractModule
{
    public function a1() { /* ... */ }
}

class ModuleB extends AbstractModule
{
    public function b1() { /* ... */ }
    public function b2() { /* ... */ } 
}

class ModuleC extends AbstractModule
{
    public function c1() { /* ... */ }
    public function c2() { /* ... */ } 
    public function c3() { /* ... */ } 
}

There is another class:
class Boss
{
    /** @var AbstractModule[] **/
    protected $_modules;

    public function __construct(array $modules)
    {
        $this->_modules = $modules;
    }

    /**
     * Последовательно запускает выполнение всех методы всех модулей с соблюдением условий.
     */
    public function process()
    {
        // ...
    }
}

It is required to implement the process method (with the necessary changes to the ModuleA, ModuleB, ModuleC and AbstractModule classes), which will execute all the methods of all modules from the $this->_modules array, subject to certain conditions, for example:
  • If there is a ModuleA in the $this->_modules array, then its ModuleA::a1 method must be executed first.
  • If the $this->_modules array contains ModuleB and ModuleC, then the ModuleB::b2 method must be executed no earlier than ModuleC::c3, but no later than ModuleC::c2.
  • If the $this->_modules array contains a ModuleB module, then the ModuleB::b1 method must be executed no earlier than ModuleB::b2.

For given conditions, the methods can be executed in the following order:
ModuleA::a1()
ModuleC::c1()
ModuleC::c3()
ModuleB::b2()
ModuleB::b1()
ModuleC::c2()
The conditions themselves can be described inside modules, but not inside the Boss class, because new modules may appear that the Boss class knows nothing about, except that they inherit from AbstractModule.
How would you implement something like this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Sundukov, 2014-05-14
@alekciy

In Module* add a public method that returns the rules. In process, for each loaded module, call such a method, and then form a launch sequence. In fact, although Boss does not know these rules, in the course of calling process, he essentially learns them. As a result, Boss does know the sequence, just indirectly.

I
Ilya Lesnykh, 2014-05-14
@Aliance

I think that it is necessary to set the priority of methods inside the class and the priority of classes inside the heir, then before cyclic execution - sort by this priority.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question