What are possible use scenarios for Traits in PHP? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
traits in php – any real world examples/best practices?
In what kind of situations would one use Traits in PHP? I do have a pretty good overall idea of this, but I can't seem to think of a way to use them in an application I have written, but that may be because it does not need traits at the time.
One scenario I have realized that needs traits:
Events. Instead of having one class that implements the observer pattern and letting all other classes inheriting it, just make it a trait and let classes that want to fire events or subscribe to use the trait. For example, the Yii framework is doing it wrong by implementing stuff at CComponent class rather than using a Trait.
Basically functionality that can be shared among classes, but may spread along multiple class hierarchies should use traits. What other scenarios could take advantage of Traits than an event system?

The issue that Traits addresses is similar to the one that Java addresses with interfaces - how to enforce common behaviour (as represented by interfaces) among classes that are not in the same class hierarchy.
With languages such as C++ which only have inheritance, for two objects from two different classes to be used in the same context requiring the same behaviour, the two classes had to be from the same hierarchy. This sometimes meant creating quite artificial hierarchies simply to allow objects from different classes to be used in the same context.
Java tackled this problem through interfaces - an interface is essentially a contract governing the provision of behaviour so that an object of one class can be substituted for an object of a separate class because it promises the same behaviour - the interface. But they don't have to be from the same hierarchy.
PHP Traits embody this idea. A trait is a kind of interface, a set of behaviours that a class contains so that it can be used in a context that requires that behaviour. So, any Java interface example should carry over to a PHP Traits example. PHP Traits are a bit different to Java interfaces, though, since Traits can contain full function definitions, whereas Java interfaces can only contain declarations (typical PHP idiosyncrasy!)

Related

UML representation of PHP trait

I'm creating projects with Symfony2/Doctrine and try to implement traits.
So far no problem on small tryouts, but I usually do UML class and sequence diagrams before deep in complex projects.
What is the UML design object(s) to be used to symbolize PHP traits, which can be seen as far as I know as behaviors? Is ther any clean way to do so?
Thanks a lot for your answers !
Nicolas
PHP Trait is basically UML Abstract Class or UML Class Template connected to the used-in class with the UML Generalization Relationship utilizing the multiple inheritance notation
See also:
Figure "UML Diagram with a Trait" in article Brendan Bates: Traits: The Right Way
Programmers: Is there a representation for mixins or traits on UML?
PHP Manual → Language Reference → Classes and Objects → Traits
As of PHP 5.4.0, PHP implements a method of code reuse called Traits.
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
In the earliest paper that I've seen Roles/Traits explained, they are represented in UML with a line connecting the Role/Trait to the method/function inside the class. http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf

PHP, OOP interface and abstraction [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between an interface and abstract class?
I read a guide about the difference between interface and abstraction but i didnt understand it the guide say's:
why using exactly interface when we can use an abstract method,
the answer is that the using of interface not require us to inherit from certain abstract class,
Thus two classes that not inherit from the same class can contain similar interface,
Actually using interface allowing us not inflate the parent class with redundant methods.
i was really tying to understand it but it did not register, if some one can please help me here i will be very thankful.
Some recommendations on when to use an interface and an abstract class (courtesy: MSDN)
1) If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
2)If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
3) If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
4) If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
http://msdn.microsoft.com/en-us/library/scsyfw1d%28v=vs.71%29.aspx
An interface allows you to have polymorphism based on similar collections of methods across several unrelated class hierarchies. This means that you can code a method to use any one of a whole range of classes which are not necessarily related to each other. You can also mix and match by having more than one interface applied to a class, so the class can be used for many things.
By contrast, abstract methods only allow you to use direct descendants of the parent class interchangeably, which can be limiting as you can't then have more than one collection of behaviours (because classes can only have one parent).

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.

Concept of Modules in php similar to Ruby

Is there something similar to the ruby module construct in php ?
Basically I need to create a modules for a mix-in b/w different classes etc.
I know that php has the concept of mixins b/w different classes, but not sure about modules.
PHP doesn't have mixins in the same way Ruby has them. That is, you can't change anything about a class after it's been defined, and you can't sanely add new methods to an instance after it's been created 1. PHP only has the plain old vanilla single-inheritance mechanism, interfaces, and composing traits in 5.4.
The closest thing that PHP might have to a Ruby module is going to be a class. The closest thing that PHP might have to a Ruby mixin is a trait, but traits are not dynamic. They must be referenced by any implementing class at the time that the class is defined. They can not be added or modified at runtime, and apply to the class as a whole, not to individual instances.
While PHP 5.3 has namespaces, they are restricted to holding functions, classes, constants, traits and interfaces only, meaning you can't define variables as a first-class member of a namespace. Attempting to do so results in them being defined in the root namespace instead, which is certainly not what anybody would want. Further, there is no namespace inheritance mechanism, only a namespace reference mechanism.
1: While you can add instance variables (properties) after an object has been created by simply referencing them, this is considered a bad practice. Properties can also contain anonymous functions, but abusing properties this way to emulate adding methods is also bad practice.

Why should I create Interfaces in PHP? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the point of interfaces in PHP?
Why should I create Interfaces in PHP?
As I understands, interfaces are there to describe classes that implement them. The classes have to contain at least these functions. This is all fine if you're building upon someone else's work, or have to maintain a degree of compatibility. But in more simplistic cases?
I know, that for the compiled programming languages, like C++, usage of interfaces allows for an increase in compiling speed, but what about PHP? This advantage seems to disappear, since PHP is interpreted, rather than compiled.
Interfaces are a way of 'emulating' multiple inheritance. A class in PHP can extend only one parent class, but can implement any number of interfaces, thus allowing you to create objects having many different types.
Perhaps a real world example will help to illustrate this. Imagine you need to build a series of logging classes that record messages to various media such as a text file, XML or a database. Each class needs to have separate code to interact with the different types of storage of course. However if they all implement the same interface the 'public face' that they show to other code is always the same. In that way other code that uses logging objects doesn't need to know what class they are instances of or what the storage medium is. All that they need to know is that all of the logging classes, by virtue of the fact that they all implement the same interface, share a common API. This can be a very powerful way of working. You can build up a library of code that solves related problems in different ways and simply 'plug and play' these in your code.
Interfaces are used to extend/emulate core PHP behavior, like iterators, array access, etc. This is the major thing that interfaces give you... that is, you cannot do it any other way.
You can also use interfaces to enforce parameter checks:
function foo(MyInterface $obj)
{
}
While not as useful as compile time checks that you would gain in another language (e.g., C++), the run time check can still be very useful in minimizing bugs.
Finally, interfaces can simplify some logic by using the is_a function or instanceof operator. You can just check if the "abstract" object implements a certain interface, and then do something accordingly.
The usage of interfaces has nothing to do with speed and will never will.
But it has a lot to do with decoupling and abstractization.
You will use them 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 - see #konforce answer
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 off right now
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 might be called for that interface, and that’s all. So the interface is used to establish a “protocol” between classes.

Categories