Concept of Modules in php similar to Ruby - php

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.

Related

PHP Trait versus Require or Include

I'd like to understand why discussions of Traits never seem to include comparison with Require, but always compare with inheritance.
It's my understanding that Require is essentially the same as a copy/paste at runtime, and Require_Once ensures the code is not repeated. Traits are also often referred to as nearly identical to copy/paste.
That said, Require and Include can be used in conditional logic, so in some circumstances they can be a better alternative to a Trait. And Traits have polymorhic and other desirable features that are not available with strict copying of code. For example, the ability to abstract a function in the trait and then optionally override in a container class.
Both of these "code inclusion/import" features have similar behavior when it comes to scope, like with $this.
But a distinct difference is that Include/Require code drops to HTML processing by default, and <?php is optional depending on the context, where with a Trait we know the code must be PHP and must be prefixed with <?php.
So to me, a Trait is more of a higher-level OOP tool while Require is a language-level directive that is not aware of OOP details. And yet, in many cases it seems it would be just as easy and useful to Require code rather than use a Trait to contain the same code.
I'm hoping someone can provide clear-cut examples where one would be chosen over the other, to make it more obvious which one should be used. There are details beyond those that I've cited. Am I already on the right path to making these choices? Is it simpler than this, or more complex? A comparison table would be ideal.
You are correct in that traits are OOP, and require is not, and while I can see how you got there (i.e. both include code) they really aren’t designed for the same use cases at all.
While require does in fact pull in code, I use it almost exclusively like I use an ‘include’ in C++ (my company uses both extensively) – to pull in lists of common defines, and to pull in the parent class for a child. A trait, would not do either of those things. For example, you have to require/include the trait file in order to use it in the desired class def.
A trait is PHP’s way of getting around not having multiple inheritance (as in C++) or a mixin (Java’s ‘fix’ for no multiple inheritance). A trait is typically paired with an interface which is included in the classses that are consumers of the trait.
I’ve used traits extensively (there are strong arguments for and against their use, but I like them), especially with reflection, to provide common behaviours within, and most especially, across class families. For example, in a simple case, I’ve used a trait to provide ‘to html’ functionality for disparate classes – a DB mirror (RDBMS interface), a flat-file mirror that I didn’t wish to force having a common base class. I see no reasonable OOP way to do that with a require. I think sprinkling requires with conditional logic in the body of a class to provide methods, though I guess you could, would be very bad form. If I were interviewing such a programmer I would probably stop at that point.
TLDR – Traits are the PHP OOP method (no pun intended) to provide common methods across classes to avoid artificial common ancestors. Requires pull in defines and parent classes.

How should I avoid the need for multiple class inheritance

I happened to need to extend my class from two others:
My PDOUser class that provides basic PDO helper functions like getRow, query, mysql_error and so on.
My Debuggable class, that provides debugging methods and error methods to print out nice debug and error messages.
I was taught that inheriting multiple classes is a confusing way to make programs and that's why PHP doesn't support it.
Why I wouldn't dare to doubt the advices of more experienced programmers, I can't see a way to solve my problem nicer.
I can't make any of the classes static. The PDOUser class provides protected property pdo that can be also accessed from child classes.
The debugger class accesses the current classes names and method names to provide useful debug info.
I could make one of the helper classes inherit the other, but I think that would be confusing as well.
You can use composition over inheritance. This decouples yours objects.
Your new class doesn't need to inherit two classes, it can hold them as instances and use their functionality.
Inheritance vs. Composition:
Wikipedia
Javaworld

What is the difference between Modules in js and Classes in php?

I am learning about modules online and it seems like modules in js and classes in php are very similar. Both group functions together for easier to understand coding. Functions can be declared in both and made public or private. How are they similar in use and how are they different?
Javascript's modules provides some nice features like encapsulation, the private state and even inheritance from other modules. While they provide some of the features of classes, as in PHP, they are not. They try to build on the existing Javascript functonality to emulate classes, hence why the confusion. i.e. they are built to look and feel like classes.
Javascript's modules are instances of an anonymous function assigned to a variable. Therefore they have all the features of a function where their code is executed top to bottom, they have and sometimes use a return statement (in PHP classes no statements can be run directly apart from field definition and assignment) and they even have access to global variables. In PHP, on the other hand a class, or rather it's methods, cannot access a variable that is not in the class itself. In order to access global variables a class method or static function has to explicitly call the variable i.e global $a inorder to import it. In js modules, all global vars are accessible but sometimes one chooses to explicity import them for neater code (function(a){})(imported);
Another important issue is data abstraction. While js modules provide private states for the fields, PHP's classes, just like C++, java, python etc, provide more security to the properties. It allows for base classes using the abstract class and interface keywords whereby class methods and attributes are only defined or structured but not used.
PHP classes also have constructors and destructors, that are called when the class object is initialized and on the last mention used to destroy the object. Granted, you can create functions in modules to run when you want, in PHP on the other hand, functions in the method are only executed when they are called either by the object, the class or other functions.
In classes there are static functions, these can be called without even having an object of the class and run independent of objects, on the other hand in js, everything is an object; which defeats the point of static functions.
They are similar in that: both have inheritance, where you can extend an existing module with a new one, and in PHP you can use extends to inherit from a parent class. They both have private data states preventing external access, they both group and package data and methods, and both are awesome when utilized properly.

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 are possible use scenarios for Traits in PHP? [duplicate]

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

Categories