99

I'm looking for a good, clean way to go around the fact that PHP5 still doesn't support multiple inheritance. Here's the class hierarchy:

Message
-- TextMessage
-------- InvitationTextMessage
-- EmailMessage
-------- InvitationEmailMessage

The two types of Invitation* classes have a lot in common; i'd love to have a common parent class, Invitation, that they both would inherit from. Unfortunately, they also have a lot in common with their current ancestors... TextMessage and EmailMessage. Classical desire for multiple inheritance here.

What's the most light-weight approach to solve the issue?

Thanks!

Alex Weinstein
  • 9,823
  • 9
  • 42
  • 59
  • 4
    There are not many cases in which inheritance (or even multiple inheritance) is justifiable. Look at SOLID principles. Prefer composition over inheritance. – Ondřej Mirtes May 23 '12 at 21:07
  • 2
    @OndřejMirtes what do you mean - "not many cases in which inheritance is justifiable."? – Tyler Oct 21 '12 at 06:53
  • 12
    I mean - inheritance brings more problems than benefits (look at Liskov substitution principle). You can solve almost everything with composition and save a lot of headaches. Inheritance is also static - that means you cannot change what is written already in the code. But compositition can be used at runtime and you can choose implementations dynamically - e. g. reuse the same class with different caching mechanisms. – Ondřej Mirtes Oct 21 '12 at 18:11
  • 5
    PHP 5.4 has "traits": http://stackoverflow.com/a/13966131/492130 – f.ardelian Jun 17 '13 at 08:48
  • @OndřejMirtes: LSP does not inherently conflict with multipe inheritance. E.g., a `Triangle` can perfectly be a `Finite` (with function `boundingRectangle`) as well as a `Intersectable` (with function `intersects`) without interfering with LSP at all. – Sebastian Mach Feb 10 '16 at 12:36
  • 1
    I would suggest beginners to **never use inheritance**. In general, the only two situations in which inheritance is allowed are: 1) when building a library, so users write less code and 2) when the project lead demands you use it – gurghet Aug 24 '16 at 15:05
  • I would agree that inheritance is almost more trouble than it's worth in PHP, as opposed to, say, C++. Also, PHP traits are a bother. However, I draw the limit of avoidance at classes. Both static and dynamic classes are excellent for grouping related functions together and keeping the global function name space clean. And they are way more consistent in this than are Namespaces. – David Spector Jan 30 '23 at 02:13

11 Answers11

144

Alex, most of the times you need multiple inheritance is a signal your object structure is somewhat incorrect. In situation you outlined I see you have class responsibility simply too broad. If Message is part of application business model, it should not take care about rendering output. Instead, you could split responsibility and use MessageDispatcher that sends the Message passed using text or html backend. I don't know your code, but let me simulate it this way:

$m = new Message();
$m->type = 'text/html';
$m->from = 'John Doe <jdoe@yahoo.com>';
$m->to = 'Random Hacker <rh@gmail.com>';
$m->subject = 'Invitation email';
$m->importBody('invitation.html');

$d = new MessageDispatcher();
$d->dispatch($m);

This way you can add some specialisation to Message class:

$htmlIM = new InvitationHTMLMessage(); // html type, subject and body configuration in constructor
$textIM = new InvitationTextMessage(); // text type, subject and body configuration in constructor

$d = new MessageDispatcher();
$d->dispatch($htmlIM);
$d->dispatch($textIM);

Note that MessageDispatcher would make a decision whether to send as HTML or plain text depending on type property in Message object passed.

// in MessageDispatcher class
public function dispatch(Message $m) {
    if ($m->type == 'text/plain') {
        $this->sendAsText($m);
    } elseif ($m->type == 'text/html') {
        $this->sendAsHTML($m);
    } else {
        throw new Exception("MIME type {$m->type} not supported");
    }
}

To sum it up, responsibility is split between two classes. Message configuration is done in InvitationHTMLMessage/InvitationTextMessage class, and sending algorithm is delegated to dispatcher. This is called Strategy Pattern, you can read more on it here.

Andre Miras
  • 3,580
  • 44
  • 47
Michał Niedźwiedzki
  • 12,859
  • 7
  • 45
  • 47
  • 15
    Amazingly extensive answer, thank you! I learned something today! – Alex Weinstein Sep 22 '08 at 04:22
  • 27
    ...I know this is a bit old (I was searching to see if PHP had MI... just for curiosity) I don't think this is a good example of the Strategy Pattern. The Strategy Pattern is designed so that you can implement a new "strategy" at any time. The implementation you have provided does not feature such ability. Instead, Message should have the "send" function which calls MessageDispatcher->dispatch() (Dispatcher either a param or member var), and new classes HTMLDispatcher & TextDispatcher will implement "dispatch" in their respective ways (this allows other Dispatchers to do other work) – Terence Honles Mar 02 '10 at 00:55
  • 13
    Unfortunately PHP is not great for implementing Strategy pattern. Languages that support method overloading work better here - imagine you have two methods of the same name: dispatch(HTMLMessage $m) and dispatch(TextMessage $) - now in strongly typed language compiler/interpreter would automatically employ the right "strategy" based on type of parameter. Aside from that, I don't think that being open for new strategy implementation is the essence of Strategy Pattern. Sure it's a nice thing to have, but often not a requirement. – Michał Niedźwiedzki Mar 03 '10 at 01:35
  • Your example is very good, and it's a good workaround. But, like all Php stuff, it's always *workaround*. Getting close to hacking (like `traits` for example). It's never part of good programming, and adds useless complexity to implement what *should be* part of a good language. More on this in the second comment. – Olivier Pons Jun 07 '14 at 15:03
  • 2
    Suppose you have a class `Tracing` (this is just a sample) where you want to have generic things like debug into a file, send SMS for critical problem and so on. All your classes are children of this class. Now suppose you want to create a class `Exception` that should have those functions (= child of `Tracing`). This class must be a child of `Exception`. How do you design such stuff *without* multiple inheritance? Yes, you always may have a solution, but you will always get close to hacking. And hacking = expensive solution in the long run. End of story. – Olivier Pons Jun 07 '14 at 15:04
  • 1
    Olivier Pons, I don't think that subclassing Tracing would be the correct solution for your use case. Something as simple as having an abstract Tracing class with static methods Debug, SendSMS, etc., which can then be called from within any other class with Tracing::SendSMS() etc. Your other classes are not 'types of' of Tracing, they 'use' Tracing. Note: some people may prefer a singleton over static methods; I prefer to use static methods over singletons where possible. –  Mar 23 '15 at 17:20
  • 1
    Olllllllllld answer but the dispatch class having to know the innards of message class is still a no-no. AND adding a new message type will require altering of dispatch class. Strong coupling. – Ejaz Jul 08 '18 at 13:24
15

Maybe you can replace an 'is-a' relation with a 'has-a' relation? An Invitation might have a Message, but it does not necessarily need to 'is-a' message. An Invitation f.e. might be confirmed, which does not go well together with the Message model.

Search for 'composition vs. inheritance' if you need to know more about that.

Matthias Kestenholz
  • 3,300
  • 1
  • 21
  • 26
10

If I can quote Phil in this thread...

PHP, like Java, does not support multiple inheritance.

Coming in PHP 5.4 will be traits which attempt to provide a solution to this problem.

In the meantime, you would be best to re-think your class design. You can implement multiple interfaces if you're after an extended API to your classes.

And Chris....

PHP doesn't really support multiple inheritance, but there are some (somewhat messy) ways to implement it. Check out this URL for some examples:

http://www.jasny.net/articles/how-i-php-multiple-inheritance/

Thought they both had useful links. Can't wait to try out traits or maybe some mixins...

Community
  • 1
  • 1
Simon East
  • 55,742
  • 17
  • 139
  • 133
7

The Symfony framework has a mixin plugin for this, you might want to check it out -- even just for ideas, if not to use it.

The "design pattern" answer is to abstract the shared functionality into a separate component, and compose at runtime. Think about a way to abstract out the Invitation functionality out as a class that gets associated with your Message classes in some way other than inheritance.

Alexandre Cox
  • 510
  • 3
  • 9
joelhardi
  • 11,039
  • 3
  • 32
  • 38
4

I'm using traits in PHP 5.4 as the way of solving this. http://php.net/manual/en/language.oop5.traits.php

This allows for classic inheritance with extends, but also gives the possible of placing common functionality and properties into a 'trait'. As the manual says:

Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

MatthewPearson
  • 301
  • 3
  • 4
3

This is both a question and a solution....

What about the magical _call(),_get(), __set() methods? I have not yet tested this solution but what if you make a multiInherit class. A protected variable in a child class could contain an array of classes to inherit. The constructor in the multi-interface class could create instances of each of the classes that are being inherited and link them to a private property, say _ext. The __call() method could use the method_exists() function on each of the classes in the _ext array to locate the correct method to call. __get() and __set could be used to locate internal properties, or if your an expert with references you could make the properties of the child class and the inherited classes be references to the same data. The multiple inheritance of your object would be transparent to code using those objects. Also, internal objects could access the inherited objects directly if needed as long as the _ext array is indexed by class name. I have envisioned creating this super-class and have not yet implemented it as I feel that if it works than it could lead to developing some vary bad programming habits.

  • I think this is feasible. It will combine functionality of multiple classes, but will not actually inherit them (in the sense of `instanceof`) – user102008 Jul 21 '11 at 05:11
  • And this will surely fail to allow overrides as soon as in inner class makes a call to self:: – Phil Lello Mar 07 '15 at 18:38
3

It sounds like the decorator pattern may be suitable, but hard to tell without more details.

danio
  • 8,548
  • 6
  • 47
  • 55
1

I have a couple of questions to ask to clarify what you are doing:

1) Does your message object just contain a message e.g. body, recipient, schedule time? 2) What do you intend to do with your Invitation object? Does it need to be treated specially compared to an EmailMessage? 3) If so WHAT is so special about it? 4) If that is then the case, why do the message types need handling differently for an invitation? 5) What if you want to send a welcome message or an OK message? Are they new objects too?

It does sound like you are trying combine too much functionality into a set of objects that should only be concerned with holding a message contents - and not how it should be handled. To me, you see, there is no difference between an invitation or a standard message. If the invitation requires special handling, then that means application logic and not a message type.

For example: a system I built had a shared base message object that was extended into SMS, Email, and other message types. However: these were not extended further - an invitation message was simply pre-defined text to be sent via a message of type Email. A specific Invitation application would be concerned with validation and other requirements for an invite. After all, all you want to do is send message X to recipient Y which should be a discrete system in its own right.

0

Same problem like Java. Try using interfaces with abstract functions for solving that problem

DeeCee
  • 400
  • 2
  • 6
0

PHP does support interfaces. This could be a good bet, depending on your use-cases.

Cheekysoft
  • 35,194
  • 20
  • 73
  • 86
-1

How about an Invitation class right below the Message class?

so the hierarchy goes:

Message
--- Invitation
------ TextMessage
------ EmailMessage

And in Invitation class, add the functionality that was in InvitationTextMessage and InvitationEmailMessage.

I know that Invitation isn't really a type of Message, it's more a functionality of Message. So I'm not sure if this is good OO design or not.

nube
  • 43
  • 7