I can not say that this is a question, but more of an opinion request and I am sure many others could benefit from clarifying this issue.
Here is my practical case:
I have an abstract class called DataExchangeService and a lot of sub-classes that extend this one (this is the base CONTROLLER class in my MVC Framework). The administration modules that handle data definiton (Users,Types,Sections etc) they all have the add,edit,delete,list methods with 100% similarity in most cases. I know that because I replicate them by using only search and replace. Now the thing is not all my DateExchangeService sub-classes handle data definiton so there are enough cases where I don't need the CRUD methods.
Multiple inheritance would define these CRUD methods and their behaviour in another class and would extend both these classes where it is needed, but I really do think it is tricky stuff and I do not use it (+PHP doesn't have such functionality). So what would be the best practice?
Here are the approaches that crossed my mind:
CASE A
Define a CRUDHandler class that has all these methods parametrized.
Create a property of CRUDHandler type where it is needed and also implement the CRUD interface that will force me to use these methods.
In the bodies of the implemented methods I add something like this:
public function edit($params) {
$this->params = $params;
$this->CRUDHandler->handle("edit", $this);
}
(In PHP this can be done with the __call() magic method.)
CASE B
Define class CRUDHandler as extending the base DataExchangeService.
When defining a specific type of DataExchangeService (for example
UsersExchangeService) instead of extending DataExchangeService you extend CRUDHandler,
this way you get all you want when it is needed.
So, are there any other opinions on this MultiInheritance approach?
Thanks
There is currently a popular style of thinking that says "favour composition over inheritance". There is too much information on Google to really list it all here, but let's just say that with the rare exception of the occasional abstract base class, I haven't used inheritance in 2-3 years.
The main idea is that any given class, rather than extending base classes that allow it to deliver required functionality, will have dependencies on other classes. In actual fact, to keep things SOLID, it'll have dependencies on interfaces that provide a contract that says they'll perform a function.
You then get to a point where your Controller class has services/components passed-in, which it delegates to in order to get specific jobs done.
Note you can go too far the other way as well. If you have a class that depends on lots of external services especially if not every public method on the class ends up using all of them, you might in fact have two classes after all. I.e. your controller is "violating" the single responsibility principle by doing more than one job. This is especially easy to do by accident with controllers in web frameworks because they kind of encourage it.
At this point, I reckon it's advisable to read up on:
Favour composition over inheritance.
Dependency Injection and Inversion of Control.
Inversion of Control containers (e.g. StructureMap and my personal favourite: Castle Windsor).
I was reading an article about the new features in PHP 5.4.0.
One of the most anticipated one being Traits.
Reading up on these Traits, to see what they're all about, they simply look as compiler assisted copy-paste to me; and a language provided way to use composition, very much as used in the well-known Strategy Pattern which leverages the 'favor composition over inheritance' design principle.
Am I understanding this correctly?
What other advantages might these traits provide, that makes them worthwhile instead of just using the composition design principle?
No, traits are not simply composition due the fact that the rules by which traits are "pasted" into a class are completely different.
When using Composition, there is no chance for conflicts or methods overwriting because the composite element is a completely isolated unit (an instance of some other class) you interface with via it's public API from within the consuming instance. Also, if you need to provide access from the consuming instance, you'd have to add proxy methods to delegate to the composite element.
Traits on the other hand become part of the API of the very instance they are used in. They are not subsystems in the instance. They are not even instances but just a reusable boilerplate code. One benefit this provides is satisfying interfaces with a trait, as I have shown in Traits in PHP – any real world examples/best practices?
You have to be careful about the meaning you give to composition. In the more general sense, traits are a mechanism for decomposition as well as composition.
Decomposition -- how we decompose a software base into suitable units
of reuse(code re-use, DRY).
Composition -- how we compose these units to obtain a class hierarchy
suitable for our application domain.
Traits are a mechanism for composition in the sense that they can be composed with a class. Many trait implementations would also allow for traits to be composed with one another.
The GoF mantra is "favor composition over inheritance".
All class-based languages by default favor inheritance. Object can only acquire behaviours from their class or from classes higher in their inheritance chain. Sure you can achieve the same outcome in different ways. For instance, you can create a Manager Class (e.g., LayoutMananager) and then add a reference to it in any class that has a layable behavior/layout trait and add function that do nothing but call methods of the Manager
public function doSomething() { return layoutManager.doSomething(); }
Traits favor composition. Simple as that. The key characteristic of traits is that they live outside of the class hierarchy. You can "acquire" re-usable behaviors or traits without them coming from any of your super-class (the horizontal vs vertical distinction introduced in other posts). That's the main advantage.
The biggest issue with traits is the emergence of conflict when traits are implemented in a way that you can directly do myObject.doSomething() instead of myObject.trait1.doSometing() (directly, or indirectly as described above with layoutManager). Once you add more than one trait to a class, conflicts can easily emerge. Your implementation needs to support mechanisms like aliasing and override to help with conflict resolution. You get some overhead back.
It is not clear that the PHP implementation conform to this, but traits are also supposed to not specify any instance variables and the methods provided by traits should never directly access instance variables. (source: Adding Traits to (Statically Typed) Languages, PDF). This blog post discusses this. It claims that in PHP, the structure named trait really is a mixin (that is traits with state). (Though this other blog post describe them as stateless)
All, in all, thinking in terms of traits is likely to help write with better code. Writing your traits classes to avoid instantiation could also contribute to better code. This frees traits from any dependency, making it possible to call them in any order. But it is not clear that adding the concept of trait in the language itself would contribute to better code.
The traits "composition" (it's merely an include on the method level of classes) happens at compile time, whereas the composition you talk about is at runtime.
When you do that composition, the trait has already been there.
As the single inheritance in PHP and as well the often seen static utility classes hinder some design goals, traits offer another facet to shape your implementation and allow to reduce code-duplication.
traits are synonym of behaviour more than inheritance or decoration.
It is not the same thing as strategy pattern because you can define a generic algorithme whereas each concrete strategy object has different algorithm.
Moreover it is more a "horizontal" inheritance of a behaviour than a "vertical" inheritance with a specification of a behaviour.
The question is reallty interesting.
I can not say that this is a question, but more of an opinion request and I am sure many others could benefit from clarifying this issue.
Here is my practical case:
I have an abstract class called DataExchangeService and a lot of sub-classes that extend this one (this is the base CONTROLLER class in my MVC Framework). The administration modules that handle data definiton (Users,Types,Sections etc) they all have the add,edit,delete,list methods with 100% similarity in most cases. I know that because I replicate them by using only search and replace. Now the thing is not all my DateExchangeService sub-classes handle data definiton so there are enough cases where I don't need the CRUD methods.
Multiple inheritance would define these CRUD methods and their behaviour in another class and would extend both these classes where it is needed, but I really do think it is tricky stuff and I do not use it (+PHP doesn't have such functionality). So what would be the best practice?
Here are the approaches that crossed my mind:
CASE A
Define a CRUDHandler class that has all these methods parametrized.
Create a property of CRUDHandler type where it is needed and also implement the CRUD interface that will force me to use these methods.
In the bodies of the implemented methods I add something like this:
public function edit($params) {
$this->params = $params;
$this->CRUDHandler->handle("edit", $this);
}
(In PHP this can be done with the __call() magic method.)
CASE B
Define class CRUDHandler as extending the base DataExchangeService.
When defining a specific type of DataExchangeService (for example
UsersExchangeService) instead of extending DataExchangeService you extend CRUDHandler,
this way you get all you want when it is needed.
So, are there any other opinions on this MultiInheritance approach?
Thanks
There is currently a popular style of thinking that says "favour composition over inheritance". There is too much information on Google to really list it all here, but let's just say that with the rare exception of the occasional abstract base class, I haven't used inheritance in 2-3 years.
The main idea is that any given class, rather than extending base classes that allow it to deliver required functionality, will have dependencies on other classes. In actual fact, to keep things SOLID, it'll have dependencies on interfaces that provide a contract that says they'll perform a function.
You then get to a point where your Controller class has services/components passed-in, which it delegates to in order to get specific jobs done.
Note you can go too far the other way as well. If you have a class that depends on lots of external services especially if not every public method on the class ends up using all of them, you might in fact have two classes after all. I.e. your controller is "violating" the single responsibility principle by doing more than one job. This is especially easy to do by accident with controllers in web frameworks because they kind of encourage it.
At this point, I reckon it's advisable to read up on:
Favour composition over inheritance.
Dependency Injection and Inversion of Control.
Inversion of Control containers (e.g. StructureMap and my personal favourite: Castle Windsor).
at my working place (php only) we have a base class for database abstraction. When you want to add a new database table to the base layer, you have to create a subclass of this base class and override some methods to define individual behaviour for using this table. The normal behaviour should stay the same.
Now I have seen many new programmers at our company, who just override the method for the default behaviour. Some are so "nice" to put in all the default behaviour and just add there individual stuff where they like it, others kill themself trying to use the baseclass and their inheritor.
My first thought to solve this problem, was thinking about abstract methods that should be overriden by inheriting classes. But beside other arguments against abstract methods, "abstract" just does not show why the baseclass can't be used by its own and why these function should be overriden.
After some googling around I didn't find a good answer to implementing "real" virtual functions in php (just that there is a virtual function, that nearly kills all hope of a concrete implementation).
So, what would you do with this matter?
In PHP all public and protected functions are "virtual". You can prevent functions from being overriden by prepending the final keyword. (Or by making them private, but this is probably a bad idea).
In the design of the baseclass I would think of behaviors that subclasses would want to affect.
I would for example create empty functions like before_update() and after_insert().
function after_insert() {
// Virtual
}
Which the baseclass will call when an update/insert event occurs.
Maybe an is_valid() function which always returns true in the baseclass, and use the commentblock to describe what the consequences are when a subclass return false.
Hopefully this would give you some inspiration.
You can always use the "final" keyword to prevent some of the classes functions from being overridden if people are using the class in the wrong way.
It sounds to me like they are unable to acheive certain functionality hence overriding the methods. You may need to take a look at the design of your classes.
Without an example of the implementation of your base class, it's hard to give concrete info. But a few things come to mind:
Database abstraction is complex stuff to begin with. I understand that you want to keep it lean, clean and mean, but I think it's pretty darn difficult. You really have to take a thorough look at the specs of different DB engines to see what parts are general and what parts need specialization. Also; are you sure you don't have DB abstraction mixed up with the Table Data Gateway pattern, as you are talking about adding DB tables by extending the base class?
The methods of your current base class might be doing too much and/or are not general enough to begin with, if the extended classes are bending over backwards too keep it clean. Maybe you should break the base class interface methods up in smaller protected methods that are general enough to be reused in the overriding methods of the extended classes? Or vice versa: maybe you should have hooks to overridable methods in your interface methods.
Following from point 2: What's wrong with having an abstract class with some general implemented methods, and let your vanilla class (your base class) and other classes inherit from that?
Lastly, maybe you should just enforce an interface to be implemented, in stead of extending the base class?
Interfaces allow you to create code which defines the methods of classes that implement it. You cannot however add any code to those methods.
Abstract classes allow you to do the same thing, along with adding code to the method.
Now if you can achieve the same goal with abstract classes, why do we even need the concept of interfaces?
I've been told that it has to do with OO theory from C++ to Java, which is what PHP's OO stuff is based on. Is the concept useful in Java but not in PHP? Is it just a way to keep from having placeholders littered in the abstract class? Am I missing something?
The entire point of interfaces is to give you the flexibility to have your class be forced to implement multiple interfaces, but still not allow multiple inheritance. The issues with inheriting from multiple classes are many and varied and the wikipedia page on it sums them up pretty well.
Interfaces are a compromise. Most of the problems with multiple inheritance don't apply to abstract base classes, so most modern languages these days disable multiple inheritance yet call abstract base classes interfaces and allows a class to "implement" as many of those as they want.
The concept is useful all around in object oriented programming. To me I think of an interface as a contract. So long my class and your class agree on this method signature contract we can "interface". As for abstract classes those I see as more of base classes that stub out some methods and I need to fill in the details.
Why would you need an interface, if there are already abstract classes?
To prevent multiple inheritance (can cause multiple known problems).
One of such problems:
The "diamond problem" (sometimes referred to as the "deadly diamond of
death") is an ambiguity that arises when two classes B and C inherit
from A and class D inherits from both B and C. If there is a method
in A that B and C have overridden, and D does not override it, then
which version of the method does D inherit: that of B, or that of C?
Source: https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem
Why/When to use an interface?
An example... All cars in the world have the same interface (methods)... AccelerationPedalIsOnTheRight(), BrakePedalISOnTheLeft(). Imagine that each car brand would have these "methods" different from another brand. BMW would have The brakes on the right side, and Honda would have brakes on the left side of the wheel. People would have to learn how these "methods" work every time they would buy a different brand of car. That's why it's a good idea to have the same interface in multiple "places."
What does an interface do for you (why would someone even use one)?
An interface prevents you from making "mistakes" (it assures you that all classes which implement a specific interface, will all have the methods which are in the interface).
// Methods inside this interface must be implemented in all classes which implement this interface.
interface IPersonService
{
public function Create($personObject);
}
class MySqlPerson implements IPersonService
{
public function Create($personObject)
{
// Create a new person in MySql database.
}
}
class MongoPerson implements IPersonService
{
public function Create($personObject)
{
// Mongo database creates a new person differently then MySQL does. But the code outside of this method doesn't care how a person will be added to the database, all it has to know is that the method Create() has 1 parameter (the person object).
}
}
This way, the Create() method will always be used the same way. It doesn't matter if we are using the MySqlPerson class or the MongoPerson class. The way how we are using a method stays the same (the interface stays the same).
For example, it will be used like this (everywhere in our code):
new MySqlPerson()->Create($personObject);
new MongoPerson()->Create($personObject);
This way, something like this can't happen:
new MySqlPerson()->Create($personObject)
new MongoPerson()->Create($personsName, $personsAge);
It's much easier to remember one interface and use the same one everywhere, than multiple different ones.
This way, the inside of the Create() method can be different for different classes, without affecting the "outside" code, which calls this method. All the outside code has to know is that the method Create() has 1 parameter ($personObject), because that's how the outside code will use/call the method. The outside code doesn't care what's happening inside the method; it only has to know how to use/call it.
You can do this without an interface as well, but if you use an interface, it's "safer" (because it prevents you to make mistakes). The interface assures you that the method Create() will have the same signature (same types and a same number of parameters) in all classes that implement the interface. This way you can be sure that ANY class which implements the IPersonService interface, will have the method Create() (in this example) and will need only 1 parameter ($personObject) to get called/used.
A class that implements an interface must implement all methods, which the interface does/has.
I hope that I didn't repeat myself too much.
The difference between using an interface and an abstract class has more to do with code organization for me, than enforcement by the language itself. I use them a lot when preparing code for other developers to work with so that they stay within the intended design patterns. Interfaces are a kind of "design by contract" whereby your code is agreeing to respond to a prescribed set of API calls that may be coming from code you do not have aceess to.
While inheritance from abstract class is a "is a" relation, that isn't always what you want, and implementing an interface is more of a "acts like a" relation. This difference can be quite significant in certain contexts.
For example, let us say you have an abstract class Account from which many other classes extend (types of accounts and so forth). It has a particular set of methods that are only applicable to that type group. However, some of these account subclasses implement Versionable, or Listable, or Editable so that they can be thrown into controllers that expect to use those APIs. The controller does not care what type of object it is
By contrast, I can also create an object that does not extend from Account, say a User abstract class, and still implement Listable and Editable, but not Versionable, which doesn't make sense here.
In this way, I am saying that FooUser subclass is NOT an account, but DOES act like an Editable object. Likewise BarAccount extends from Account, but is not a User subclass, but implements Editable, Listable and also Versionable.
Adding all of these APIs for Editable, Listable and Versionable into the abstract classes itself would not only be cluttered and ugly, but would either duplicate the common interfaces in Account and User, or force my User object to implement Versionable, probably just to throw an exception.
Interfaces are essentially a blueprint for what you can create. They define what methods a class must have, but you can create extra methods outside of those limitations.
I'm not sure what you mean by not being able to add code to methods - because you can. Are you applying the interface to an abstract class or the class that extends it?
A method in the interface applied to the abstract class will need to be implemented in that abstract class. However apply that interface to the extending class and the method only needs implementing in the extending class. I could be wrong here - I don't use interfaces as often as I could/should.
I've always thought of interfaces as a pattern for external developers or an extra ruleset to ensure things are correct.
You will use interfaces in PHP:
To hide implementation - establish an access protocol to a class of objects an change the underlying implementation without refactoring in all the places you've used that objects
To check type - as in making sure that a parameter has a specific type $object instanceof MyInterface
To enforce parameter checking at runtime
To implement multiple behaviours into a single class (build complex types)
class Car implements EngineInterface, BodyInterface, SteeringInterface {
so that a Car object ca now start(), stop() (EngineInterface) or goRight(),goLeft() (Steering interface)
and other things I cannot think of right now
Number 4 it's probably the most obvious use case that you cannot address with abstract classes.
From Thinking in Java:
An interface says, “This is what all classes that implement this particular interface will look like.” Thus, any code that uses a particular interface knows what methods can be called for that interface, and that’s all. So the interface is used to establish a “protocol” between classes.
Interfaces exist not as a base on which classes can extend but as a map of required functions.
The following is an example of using an interface where an abstract class does not fit:
Lets say I have a calendar application that allows users to import calendar data from external sources. I would write classes to handle importing each type of data source (ical, rss, atom, json) Each of those classes would implement a common interface that would ensure they all have the common public methods that my application needs to get the data.
<?php
interface ImportableFeed
{
public function getEvents();
}
Then when a user adds a new feed I can identify the type of feed it is and use the class developed for that type to import the data. Each class written to import data for a specific feed would have completely different code, there may otherwise be very few similarities between the classes outside of the fact that they are required to implement the interface that allows my application to consume them. If I were to use an abstract class, I could very easily ignore the fact that I have not overridden the getEvents() method which would then break my application in this instance whereas using an interface would not let my app run if ANY of the methods defined in the interface do not exist in the class that implemented it. My app doesn't have to care what class it uses to get data from a feed, only that the methods it needs to get that data are present.
To take this a step further, the interface proves to be extremely useful when I come back to my calendar app with the intent of adding another feed type. Using the ImportableFeed interface means I can continue adding more classes that import different feed types by simply adding new classes that implement this interface. This allows me to add tons of functionality without having to add unnecessarily bulk to my core application since my core application only relies on there being the public methods available that the interface requires so as long as my new feed import classes implement the ImportableFeed interface then I know I can just drop it in place and keep moving.
This is just a very simple start. I can then create another interface that all my calendar classes can be required to implement that offers more functionality specific to the feed type the class handles. Another good example would be a method to verify the feed type, etc.
This goes beyond the question but since I used the example above:
Interfaces come with their own set of issues if used in this manner. I find myself needing to ensure the output that is returned from the methods implemented to match the interface and to achieve this I use an IDE that reads PHPDoc blocks and add the return type as a type hint in a PHPDoc block of the interface which will then translate to the concrete class that implements it. My classes that consume the data output from the classes that implement this interface will then at the very least know it's expecting an array returned in this example:
<?php
interface ImportableFeed
{
/**
* #return array
*/
public function getEvents();
}
There isn't much room in which to compare abstract classes and interfaces. Interfaces are simply maps that when implemented require the class to have a set of public interfaces.
Interfaces aren't just for making sure developers implement certain methods. The idea is that because these classes are guaranteed to have certain methods, you can use these methods even if you don't know the class's actual type. Example:
interface Readable {
String read();
}
List<Readable> readables; // dunno what these actually are, but we know they have read();
for(Readable reader : readables)
System.out.println(reader.read());
In many cases, it doesn't make sense to provide a base class, abstract or not, because the implementations vary wildly and don't share anything in common besides a few methods.
Dynamically typed languages have the notion of "duck-typing" where you don't need interfaces; you are free to assume that the object has the method that you're calling on it. This works around the problem in statically typed languages where your object has some method (in my example, read()), but doesn't implement the interface.
In my opinion, interfaces should be preferred over non-functional abstract classes. I wouldn't be surprised if there would be even a performance hit there, as there is only one object instantiated, instead of parsing two, combining them (although, I can't be sure, I'm not familiar with the inner workings of OOP PHP).
It is true that interfaces are less useful/meaningful than compared to, say, Java. On the other hand, PHP6 will introduce even more type hinting, including type hinting for return values. This should add some value to PHP interfaces.
tl;dr: interfaces defines a list of methods that need to be followed (think API), while an abstract class gives some basic/common functionality, which the subclasses refine to specific needs.
I can't remember if PHP is different in this respect, but in Java, you can implement multiple Interfaces, but you can't inherit multiple abstract classes. I'd assume PHP works the same way.
In PHP you can apply multiple interfaces by seperating them with a comma (I think, I don't find that a clean soloution).
As for multiple abstract classes you could have multiple abstracts extending each other (again, I'm not totally sure about that but I think I've seen that somewhere before). The only thing you can't extend is a final class.
Interfaces will not give your code any performance boosts or anything like that, but they can go a long way toward making it maintainable. It is true that an abstract class (or even a non-abstract class) can be used to establish an interface to your code, but proper interfaces (the ones you define with the keyword and that only contain method signatures) are just plain easier to sort through and read.
That being said, I tend to use discretion when deciding whether or not to use an interface over a class. Sometimes I want default method implementations, or variables that will be common to all subclasses.
Of course, the point about multiple-interface implementation is a sound one, too. If you have a class that implements multiple interfaces, you can use an object of that class as different types in the same application.
The fact that your question is about PHP, though, makes things a bit more interesting. Typing to interfaces is still not incredibly necessary in PHP, where you can pretty much feed anything to any method, regardless of its type. You can statically type method parameters, but some of that is broken (String, I believe, causes some hiccups). Couple this with the fact that you can't type most other references, and there isn't much value in trying to force static typing in PHP (at this point). And because of that, the value of interfaces in PHP, at this point is far less than it is in more strongly-typed languages. They have the benefit of readability, but little else. Multiple-implementation isn't even beneficial, because you still have to declare the methods and give them bodies within the implementor.
Interfaces are like your genes.
Abstract classes are like your actual parents.
Their purposes are hereditary, but in the case of abstract classes vs interfaces, what is inherited is more specific.
I don't know about other languages, what is the concept of interface there. But for PHP, I will try my best to explain it. Just be patient, and Please comment if this helped.
An interface works as a "contracts", specifying what a set of subclasses does, but not how they do it.
The Rule
An Interface can't be instantiate.
You can't implement any method in an interface,i.e. it only contains .signature of the method but not details(body).
Interfaces can contain methods and/or constants, but no attributes. Interface constants have the same restrictions as class constants. Interface methods are implicitly abstract.
Interfaces must not declare constructors or destructors, since these are implementation details on the class
level.
All the methods in an interface must have public visibility.
Now let's take an example.
Suppose we have two toys: one is a Dog, and other one is a Cat.
As we know a dog barks, and cat mews.These two have same speak method, but with different functionality or implementation.
Suppose we are giving the user a remote control that has a speak button.
When the user presses speak button, the toy have to speak it doesn't matter if it's Dog or a Cat.
This a good case to use an interface, not an abstract class because the implementations are different.
Why? Remember
If you need to support the child classes by adding some non-abstract method, you should use abstract classes. Otherwise, interfaces would be your choice.
Below are the points for PHP Interface
It is used to define required no of methods in class [if you want to load html then id and name is required so in this case interface include setID and setName].
Interface strictly force class to include all the methods define in it.
You can only define method in interface with public accessibility.
You can also extend interface like class. You can extend interface in php using extends keyword.
Extend multiple interface.
You can not implement 2 interfaces if both share function with same name. It will throw error.
Example code :
interface test{
public function A($i);
public function B($j = 20);
}
class xyz implements test{
public function A($a){
echo "CLASS A Value is ".$a;
}
public function B($b){
echo "CLASS B Value is ".$b;
}
}
$x = new xyz();
echo $x->A(11);
echo "<br/>";
echo $x->B(10);
We saw that abstract classes and interfaces are similar in that they provide abstract methods that must be implemented in the child classes. However, they still have the following differences:
1.Interfaces can include abstract methods and constants, but cannot contain concrete methods and variables.
2.All the methods in the interface must be in the public visibility
scope.
3.A class can implement more than one interface, while it can inherit
from only one abstract class.
interface abstract class
the code - abstract methods - abstract methods
- constants - constants
- concrete methods
- concrete variables
access modifiers
- public - public
- protected
- private
etc.
number of parents The same class can implement
more than 1 interface The child class can
inherit only from 1 abstract class
Hope this will helps to anyone to understand!