maddo7
maddo7

Reputation: 4973

Group functions within class

I have a class where I have similar functions that are related to different endpoints

class MyClass {

    public function case1_changeOrder() {

    }

    public function case1_changeLimit() {

    }

    public function case2_changeOrder() {

    }

    public function case2_changeLimit() {

    }


}

Is it possible to group those functions somehow so I can get rid of the prefix and do something like

$mc = new MyClass();
$mc->case1->changeOrder();
$mc->case2->changeOrder();

instead of

$mc = new MyClass();
$mc->case1_changeOrder();
$mc->case2_changeOrder();

Upvotes: 1

Views: 1234

Answers (1)

Plamen G
Plamen G

Reputation: 4759

You can achieve this with Composition, but it seems to me that it won't be good design because it is better to use composition the way it is meant to be (A has a B) not just for grouping.

If the operations are similar do it with an abstract base class and inheritance like so (you will have the added benefit of using polimorphism later if you need to):

abstract class GenericCase
{   
    abstract public function changeLimit();
    abstract public function changeOrder();
}

Then two classes that inherit from the base class:

class Case1 extends GenericCase
{
    public function changeLimit()
    {
        //... case 1 implementation
    }

    public function changeOrder()
    {
        //... case 2 implementation
    }
}

class Case2 extends GenericCase
{
    public function changeLimit()
    {
        //... case 2 implementation
    }

    public function changeOrder()
    {
        //... case 2 implementation 
    }
}

Or you can achieve the same using a common interface. It really is a matter of preference in this case. See this tutorial for more details.

If you insist of doing it with composition to have the exact structure you asked for, see section Composition - Association and Aggregation here

Good luck.

Upvotes: 2

Related Questions