Elegant alternatives to the weird multiple inheritance - php

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).

Related

Laravel reusable functions

I am using Repository design pattern and I have a function generateBarcode() this function just do some logic and insert data in database.
I am calling this function in more one function and more that one repository to generate a new Barcode.
Question is:
What is the best way to make this function reusable?
Helpers
But I don't think this is a good idea since it am dealing with database.
Events
Firing event and storing the result.
$barcode = event(new NewBarcodeRequired())
That what I am doing right now and data is returned as an array
Also I don't think that is a good idea because I have read that events shouldn't return data.
Repository
Create a new repository for this function but I think it is a very bad idea because I won't create a class for every reusable function that I have.
Traits could be a good option for this case. Which will give you flexibility to use in any of your class without requirement of class extension.
Traits are 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. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.
A Trait is similar to a class, but only intended to group
functionality in a fine-grained and consistent way. It is not possible
to instantiate a Trait on its own. It is an addition to traditional
inheritance and enables horizontal composition of behavior; that is,
the application of class members without requiring inheritance.
http://php.net/manual/en/language.oop5.traits.php

How Multiple inheritance in php [duplicate]

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).

Are traits not simply composition?

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.

What is the use of an abstract class, interface or an abstract method

I have a confusion in why we use abstract classes or interfaces to implement or extend. interfaces doesn't contain any code so does the abstract methods. then why we use them. why don't we directly create methods and define them in our class rather we use interfaces or abstract classes. they don't contain any sort of code, we need to define them after extending them in our class. why we don't define these methods in our own class rather extend interfaces and then define them. I found such type of question asked several times in stackoverflow but couldn't understand the answer. can anyone please explain it in some simple way
The power of abstraction and interfaces comes from the fact that you can separate responsibilities and write modular code: One part of your (or someone else's) code may only care that you have an Animal and provide facilities to deal with Animals, without needing to know how they move or feed. A different part of your code may only care about defining lots of concrete animals, like Dogs, Birds, etc., with all the details of how they actually implement all their features.
By making the concrete classes (Dog, Bird, ...) extend a common, abstract interface (Animal), you can use a any now and future concrete class in a library written for the abstract interface -- you don't need to ask the library author to change the library to accommodate new Animals, and the library author doesn't need to know how features are concretely implemented.
For example, if you had two single algorithm, FeedBreakfast and FeedDinner, that would require a member function Animal::gobble(), then without inheritance you would need to implement each algorithm for each animal - i.e. you'd end up with M * N amount of code! By using a common, abstract interface you reduce this to M + N -- M algorithms and N concrete classes, and neither side needs to know of the other -- they just both need to know the interface.
Statically typed languages need to use this method to enable polymorphism. That is, you can write your code in terms of your abstract base class. Then you can "plug" in any subclass as an extension. This is called Liskov Substitution principle, or Open/Closed principle. Technically, this is called dynamic binding. That is, the method to call is selected during runtime depending on the subclass.
With dynamically typed languages the situation is completely different. I don't know if PHP is dynamically typed (I suspect it is), but in Ruby or Javascript, for example, you can program in terms of any object that conforms to a specific interface. That is, if your code expects an object that has a method called Print you can substitute with any other object that also has a Print method, without deriving from a common base class. The method will be looked up during runtime, that is why these languages are called "dynamic".
Hope this helps!
You use abstract classes or interfaces when you want to establish a protocol.
It sounds simple, but it's a very powerful concept. If you are forced to adhere to rules, then you cannot break them. If you cannot break the rules, you adhere to the protocol. Therefore, all the classes that implement your interface should inherently be compatible with each other. Naturally, there are exceptions among human kind who are able to break these rules by creating code that even interpreters cry when they have to parse it but that's a bit of an offtopic :)
For an interface, imagine you have a Class called "Message". This implements the Interface called SendMessage, which has a method definition of Send.
If you then create two subclasses of "Message". One could be "Email" and one could be "InstantMessage".
Now these both have the method Send(), which is defined in the SendMessage interface, and are blank. This now allows you to define differently what the Send() method does. However, because we know the classes Email, and InstantMessage use the interface SendMessage, we know that they both have the method Send();
So you could call Email.Send(), and InstantMessage.Send(), but do two different things. An interface defines methods available to several objects, but with the same method name.
Abstract classes/interfaces are mostly design time considerations. By defining methods as abstract and therefore the classes as abstract too.. we are ensuring that these methods will definitely be implemented by deriving classes. If they do not implement them they also become abstract.
Interfaces provides the luxury of distributing the must implement methods into different categories, so the required number of interfaces can be implemented.
the abstract classes guarantee that can't be instantiate, this is because are a generalization. for example,
in a game, exist a class player, but also exist classes defender and forward. the class player is the parent class of both classes. not is practice create a object player, because a team need a especific player.
The interfaces are related with polymorphism. every class, use methods according to its behavior.
i hope this help you
The idea behind an abstract class is that you can define some common functionality of a set of similar classes, but leave other details up to the implementing (extending) classes. In a way they are similar to interfaces, except that you can actually implement some of the functions in the abstract class.
But what's the point, I hear you ask? Well, you only have to write the common code once, although you can do this in a concrete (non-abstract) base class too. But also you may not want other programmers to instantiate the base class, so this is where the real power of abstract classes come in.
Let me show an example to help illustrate my point. Imagine you are writing a program to classify all of the animals in a zoo. Animals can be classified into certain types, bird, reptile, mammal, insect, arachnid, fish, etc, and then down to their species such as dog, cat, parrot or kangaroo. The base class, Animal, can provide some of the common functionality to all of these. It might have a function called eat() which all animals do in a similar way and so the function is written out to describe the process of an animal eating. It might contain another function, walk(), but this one is abstract, since different animals will implement this in a different way. All subclasses of the Animal class will need to implement this method.
The major bonus of this is that somewhere in your code you can call a function that takes an Animal as a parameter. You know that you can call the eat() and walk() functions on this parameter because all Animals can eat and walk. This is called polymorphism and is an important trait of Object Oriented Programming.
I hope this has helped you. Please feel free to discuss or ask further questions if you still can't see the value of abstract classes.

Correct Implementation of Virtual Functions in PHP?

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?

Categories