How to solve this without multiple inheritance? - php

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.

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.

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.

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.

Related

Shared functions between already extended classes

I am looking to tidy up some code I have inherited. Essentially we have two classes (A + B) that extend off two separate classes that do various things differently, however A and B also share some functions. At present the functions are copy and pasted between the two and obviously I know this is wrong. I am looking to see if there it a solution to this so that I only have to define the functions once so that both A and B can use these. Any help would be great!
From php 5.4 you could use Traits.
Here is example from manual
<?php
trait ezcReflectionReturnInfo {
function getReturnType() { /*1*/ }
function getReturnDescription() { /*2*/ }
}
class ezcReflectionMethod extends ReflectionMethod {
use ezcReflectionReturnInfo;
/* ... */
}
class ezcReflectionFunction extends ReflectionFunction {
use ezcReflectionReturnInfo;
/* ... */
}
?>
In an ideal world, it's possible that what you really want there is multiple inheritance, but that is not supported by PHP (or many other languages) as it is much more complex than single inheritance.
One alternative to consider is arranging your code so that both classes eventually inherit from some common ancestor, so that you can put your code here. This may not always be desirable or practical, however, particularly if some of the classes extended are from different libraries with no shared dependency.
You might be able to alter the ancestry of some of your classes by using "composition" and "delegation" rather than direct inheritance. The basic idea is that rather than class B extending class A, you store an instance of class A as a property of class B; when certain methods of class B are called, they call corresponding methods of the A instance, while other methods of B are completely separate, and can be inherited from somewhere else. The magic method __call can be useful for implementing this without having to know every possible delegated method in advance.
As of PHP 5.4, there is a form of "horizontal code reuse" called Traits. Traits are sometimes described as "compiler-assisted copy-and-paste", because they don't represent any OOP relationship between the classes where they are used, only a way of editing the functions in one place.
If the functions are public, you might want to declare the classes as implementing an Interface, which lets other code check that a set of methods are available, usually by using the instanceof operator. This can be used in combination with a Trait, which contains the details of how those methods are implemented.

PHP. Use of methods in the base class which will be defined in the derived

Is it a good practice to use in the base class a method which will be defined in a derived one? For instance:
abstract class CApplication {
use TSingleton;
protected final function singletonInstanceInit() {
if (php_sapi_name() == 'cli') {
$this->initCLIApp();
}
else {
$this->initWebApp();
}
}
}
abstract class CWebApplication extends CApplication {
protected function initWebApp() { }
}
abstract class CCLIApplication extends CApplication {
protected function initCLIApp() { }
}
AFAIK this is not a good practice.
Inheritance is needed for the purpose of defining new behaviors and new specialized types of objects. Which means that you could/*should* write a base class now and extend it some time late on.
If the base class knows something about the structure of it's derived classes that's somewhat of a contract, the derived classes need to implement some functions in order to work with that base class in which case "design by contract" springs to mind.
If you need to have a certain function in the derived class maybe it should be declared as an abstract function in the base class or as a method in an interface the class implements.
That way it's not unreasonable for the base class to know about methods implemented in the derived classes.
Also AFAIK other stricter languages would not permit this at compiler level. You would really need to do some refactoring to achieve this in c++ or Java something along the lines of what I said above using abstract functions in the base class or interfaces.
What you are talking about is 2 different schools of thought. I've seen ruby developers doing such stuff because they were using mixins (yes lots of gems do that). On other hand if you go and ask a classic Java programmer he won't recommend you doing that. The type of liberty that you are just showing in your code is what only dynamic typed languages give you (Ya I know some heads would nod saying I used CGLib), they are implementable either in a hackish way for static typed languages or they are not used at all.
Long story cut short, if I were you I would look into scenario and decide if I need such black magic for my given task or not? No rule is bad as long as it doesn't hurt the code quality.

Interfaces and abstract class inheritance, implementation in extended classes

In every example I've seen, extended classes implement the interfaces of their parents. For reference, the following example:
interface MyInterface{
public function foo();
public function bar();
}
abstract class MyAbstract implements MyInterface{
public function foo(){ /* stuff */ }
public function bar(){ /* stuff */ }
}
// what i usually see
class MyClass extends MyAbstract implements MyInterface{}
// what i'm curious about
class MyOtherClass extends MyAbstract{}
Is failure to implement an interface in a child, which is implemented by a parent, considered bad practice or something? Are there any technical drawbacks to omitting the implementation in the child?
I would consider that you are on the right path. There is no need to declare that you are implementing the interface, when extending a class that already implements it. For me it's just another piece of code to maintain if change is needed. So, yes, you are correct!
Is failure to implement an interface
in a child, which is implemented by a
parent, considered bad practice or
something? Are there any technical
drawbacks to omitting the
implementation in the child?
I just can't answer your question better than this guy has:
By their nature, although sometimes
they may look quite similar, abstract
classes and class interfaces serve
very distinct purposes.
The interface of a class is meant as a
tool for the "user" of that class. An
interface is a public presentation for
the class, and it should advertise, to
anyone considering to use it, what
methods and constants are available
and accessible from the outside. So,
as it name suggests, it always sits
between the user and the class
implementing it.
On the other hand, an abstract class
is a tool aimed at helping the
"implementor" of the classes that
extend it. It is an infrastructure
that can impose restrictions and
guidelines about what the concrete
classes should look like. From a class
design perspective, abstract classes
are more architecturally important
than interfaces. In this case, the
implementor sits between the abstract
class and the concrete one, building
the latter on top of the former.
Reference
Thus, it's up to you to decide, based on who is going to use (instantiate) your classes, and who is going to write them. If you are the sole user and writer of your classes, then, maybe, just maybe, you don't need them both. But, if you want to give everyone a stripped down to core bits blueprint for the class writer(s) and class user(s), then you should consider using both abstracting and implementing.
Maybe a little late to the table but I see the above comments do not clarify the main misunderstanding underlying the OP's question.
So the underlying questions are:
Why we use both an Abstract class and an Interface on the same line?
Should both an Abstract method and an Interface declare the same methods at all?
But before some clarifications why to use either of the two above:
Either of them are used by one programmer to define the contract (requirements, obligations, limitations) the other programmers have to obey when they create the concrete classes (and eventually entire software application) based on Abstract classes / Interfaces developed by that programmer.
An Abstract class, in turn, is used to provide the later created concrete class with methods & data structures blueprint via:
data structures declarations (optional),
base implementation of methods (and their signatures, optional)
just methods declarations (similar to an Interface usage, optional).
An Interface is used to provide a concrete class with a methods blueprint via
just methods (and their signatures, optional) declarations.
Here is an example for an Abstract and concrete classes.
abstract class MyAbstractClass {
public function foo() {
// Base implementation of the method here.
}
public function bar() {
// Base implementation of the method here.
}
// Effectively similar to baz() declaration within some interface:
public abstract function baz($value);
}
class MyConcreteClass extends MyAbstractClass {
// foo() and bar() are inherited here from MyAbstractClass.
// baz() must be implemented or declared abstract again.
public function baz($value) {
// implementation.
}
}
Then the questions come:
Why we need an Interface here?
Do we need an Interface to duplicate same method declarations?
The answers:
Due to the fact that PHP allows only single inheritance for each subclass (you cannot write class MyConcreteClass extends MyAbstractClass, MyAnotherClass {}), when we need to expand the concrete class functionality beyond the already used Abstract class we have to declare this additional functionality via one or more Interfaces.
Like this:
class MyConcreteClass
extends MyAbstractClass
implements MyInterface, MyAnotherInterface {
// Methods and data implementations go here.
}
As the result from the answer 1, an Interface better not to duplicate an Abstract class methods' declarations (this is basically useless). An Interface(s) should decalre the methods that may help to enhance the concrete (or another Abstract class, why not) functionality to provide the programmer that will use these with the firm contract for each object built on top of these classes and interfaces.
Finally, answer to the the OP question whether to use an Interface for an Abstract class or for the concrete class is:
use for either or both (or as needed) as long as an Interface enhances a class contract with new methods' declarations.
Is failure to implement an interface in a child, which is implemented by a parent, considered bad practice or something?
The child always implements the interface, it can not go around with this.
I have no clue if that is bad practice or something. I would say it's a language feature.
Are there any technical drawbacks to omitting the implementation in the child?
You can not test the reflection of the abstract class for having the interface for example.
However, abstract class are already an interface, so technically they themselves not really need the interface but you can do so to keep things fluid within the inheritance.
Well, I was confused too, but I think you should use the latter one, You are right, If you implement the interface in the abstract class, then there is no need to write the interface, you can write the method in interface all into abstract as abstract methods, because you will extend the abstract class whatever, and you will have to use the abstract class as a param type when you use the class in other place, that's not a good thing, I think an abstract class should't be used as a param type, while an interface should be.

Real World Examples of Advanced OOP Features for PHP

I am trying to improve my knowledge of OOP in PHP and have been researching abstract classes and interfaces.
What I have learned
They are both classes that cannot be instantiated themselves but can olny be extended (implemented in the case of interfaces)
Abstract classes provide methods and properties for other classes that extend them.
If a class uses an abstract method then the class itself must also be abstract.
If an abstract method is defined within an abstract class, all child classes must define the details of that method. Methods not defined as abstract can be used in the same way as normal methods.
Interfaces define what methods a class that implements it must have. The functionality of the methods are not defined in the interface, the interface just offers a list of methods that must be included in the child class.
An interface does not define any properties.
Classes can implement as many interfaces as they want to but they must define a method for every one of the interfaces they implement
I think that covers the basics. Please feel free to add to that if you think there's anything I have missed.
What I would like to know is if there are any real world examples of implementation of these classes, especially the interface class. Does anyone know of any open source applications that use them that I can browse to better understand them and see where and when they are used effectively? I have come across book examples which use animals which fails to demonstrate the importance of these classes.
The final keyword prevents the class being extended by other classes, example:
class Parent
{
}
class Mother extends Parent
{
}
final class Brother extends Mother /* - This class cannot be extended - */
{
}
class Pet extends Brother
{
}
The Pet class will throw an error stating: Fatal error: Class Pet may not inherit from final class (Brother)
This is also available for methods, so if you do not want to allow the methods to be inherited causing the child class to have the same method acting as an override.
http://php.net/manual/en/language.oop5.final.php
Yo used that you would like some real world examples of what interfaces can be used for, well a database abstraction layer
You have 1 base class which provides the basic methods to iterate your database data, but that would use a sub class for the the database type, such as MySql,MsSql etc, each database type would have its own class, but for the base class to make sure that it has these methods they would all implement the same interface.
Example
interface IDatabaseLayer
{
public function connect();
public function query();
public function sanitize();
//...
}
So the base class knows that MySql and MsSql have the above methods, thus reducing errors and being more organized.
When passing in objects to classes you want to be sure that the Object is of a certain type, PHP5 allows you to define what type of object should be passed into the methods as params.
lets say you have 3 classes
DatabaseCredentials
DatabaseConnection
DatabaseQuery
you can specifically define in the constructuin of DatabaseConnection that you require a DatabaseCredentials class like so:
class DatabaseConnection implements Connectable
{
public function __construct(DatabaseCredentials $ConnectionDetails)
{
$this->Connect($ConnectionDetails->BuildDSN());
}
}
A good way to really get started is by reading here:
http://php.net/manual/en/language.oop5.php
Another feature of PHP5 you may wish to look at is name spaces, this will allow you to keep your code organized, have multiple objects with the same name, makes auto loading more efficiently
Small Example:
namespace Database\MySql
{
class Database{}
}
namespace Database\MsSql
{
class Database{}
}
And you can just use like:
use Database;
$Database = new MySql\Database();
PHP comes with few interfaces predefinded by default: http://www.php.net/manual/en/reserved.interfaces.php
PHP also contains Standard PHP Library (SPL), which defines more:
interfaces http://www.php.net/manual/en/spl.interfaces.php
classes, including abstract ones: http://www.php.net/manual/en/spl.datastructures.php
Zend Framework is also very good example where such concepts are used. http://framework.zend.com/
Not a real world example as such, but one Design Pattern where you usually encounter interfaces and abstract classes is the Command Pattern. See link for example code.
In general, "programming against an interface" is considered good OO practise, because it decouples concrete implementations and let you more easily change them for other implementations, e.g. instead of asking for a specific class
public function fn(ConcreteClass $obj)
{
$obj->doSomething()
}
you just ask that it provides a certain set of methods
public function fn(MyInterface $obj)
{
$obj->doSomething()
}
Interfaces also help teasing apart large inheritance structures. Because PHP supports only Single Inheritance, you'll often see hierarchies like this:
BaseClass -> Logger -> Auth -> User
where each of these contains specific aspects used inside these classes. With an interface, you just do
User implements Loggable, Authenticable
and then include that specific code via Strategy Patterns or Composition/Aggregation, which is ultimately much more maintainable.
For a list of predefined interfaces in PHP see my answer to:
where to find "template" interfaces?.
You may follow the "PHP patterns" series by Giorgio Sironi in dzone or directly in his blog, really interesting if you are interested patterns and OOP.
Also you could take a look to the Best PHP programming book in stackoverflow if you're in need of a good PHP book.
We can say that interface is purely 100% abstract class but abstract is not. Because many time we defines function in abstract class. But in interface class we always declare function.

Emulate multiple inheritance in php

I have a system of Models:
abstract class R00_Model_iUnique { }
abstract class R00_Model_iFamilyUnique extends R00_Model_iUnique { } // for models with hierarchy
abstract class R00_Model_iTaggedUnique extends R00_Model_iUnique { } // for models with tags
// and, for example
class R00_Model_User extends R00_Model_iUnique { }
class R00_Model_Comment extends R00_Model_iFamilyUnique { }
class R00_Model_Post extends R00_Model_iTaggedUnique { }
There is gonna be R00_Model_iCommentableUnique and R00_Model_Post wants to be inherited from it. But It isn't possible, it's already inherited from R00_Model_iTaggedUnique, and I don't think It's clever to inherit R00_Model_iTaggedUnique from R00_Model_iCommentableUnique or vice versa. I've thought up only one idea how to implement it, but I have some doubts. Maybe you can tell me about some smart methods or criticize that method?
I thought up to make R00_Model_i*Unique not classes, but interfaces, and create helper objects, such as R00_Model_Helper_iUnique (maybe it is a common patern, and there is a cool name, I don't think 'Helper' will be cool there?). Then, in R00_Model_iUnique, create __call(), which checks all the Interfaces of a called object and looks up a called method in the helper.
Or there is too many reflection and other evil slow stuff, isn't it?
You are in the right direction with using an interface and helpers (composition).
This is precisely one of the reasons why on of the principles of the Design Patterns Book (GoF) is "Favor composition over inheritance".
Composition will give you the flexibility you require to use methods of different classes
In the class that you need it.

Categories