Reputation: 21333
I have class named Controller_Home
. It should inherit from Controller_Permissions
and Controller_Template
. Any class prefixed with Controller_
must inherit from Controller
class.
If multiple inheritance would be supported in PHP (my case), I could do like this:
class Controller_Home extends Controller_Permissions, Controller_Template {
And Controller_Permissions
, Controller_Template
:
Controller_Permissions extends Controller {
Controller_Template extends Controller {
Now I need to do something like this:
class Controller_Home extends Controller_Template {
class Controller_Permissions extends Controller_Template {
Controller_Template extends Controller {
Okay, it works!
Now I need to use Controller_Template
without permissions (in Controller_Permissions
).
How to do it without duplicating code? I don't want another class Controller_TemplateWithoutPermissions
.
Controllers, templates and permissions is just for example.
Upvotes: 2
Views: 258
Reputation: 11598
There's nothing pretty about that at all. All of your classes are very tightly coupled together. Defining, and then implementing interfaces on the objects, and using aggregation to build up the 'with permissions' and 'without permissions' types is a cleaner, and 'prettier' solution. It also allows for IoC (which breaks encapsulation if you're a staunch SOLID person), which gives you better unit testing scenarios, and allows for the use of a DI container.
Upvotes: 3
Reputation: 2616
The common alternative to multiple inheritance is to use composition. This makes the relationship a "has a" as opposed to an "is a" relationship. Ie in your example above you might have ControllerHome inherit from ControllerTemplate but hold some ControllerPermissions as a variable. This way ControllerHome is a ControllerTemplate and has a ControllerPermissions.
Upvotes: 12
Reputation: 128807
You could use Traits in this situation.
Traits are similar to mixins, but whereas mixins can be composed only using the inheritance operation, traits offer a much wider selection of operations, including symmetric sum, method exclusion, and aliasing. A Trait differs from an abstract type in that it provides implementations of its methods, not just type signatures.
Traits is available in PHP 5.4 and is common in Scala.
Upvotes: 3