php traits

16
Traits in PHP The what, where, why and how

Upload: shaun-morrow

Post on 16-Aug-2015

46 views

Category:

Software


0 download

TRANSCRIPT

Traits in PHPThe what, where, why and how

On wikipedia, traits are defined as “In computer programming, a trait is a collection of methods, used as a "simple conceptual model for structuring object-oriented programs" similar to mixins. Traits provide a simple way to create classes that reuse behavior from software components.”

Short version is that they are a collection of methods that can be used by other classes and a class can use many traits.

Traits are not mixins, but traits implementation in PHP is more like mixins than traits.

But wait, theres more...

What?

Also used in other languages, such as;• Perl 6 - known as roles• Ruby - modules can be used to

implement traits• Scala• Python - using the Trait package• Smalltalk

Available from PHP 5.4

Where in the code?

Output is 16

Why?Methods in traits override extended classes

Order of precedence

Output is 8

Why?Methods defined in the class override methods in the trait

Order of precedence contd.

Output is16Message!

What if two traits have the same method names?

Multiple traits

insteadof operator is your friend!

Output will be16Other Message

We explicity told PHP to use the tCalculations trait for the getSomeMessage method

Dealing with conflicts

• Simple way to share methods among different classes• No instantiation needed• Shares scope (attributes etc.) with

including class• Helps reduce code duplication• Can improve cleanliness of code• Can be used to create multiple

inheritance scenarios

Why would you use traits?

• Can not mock for unit testing• Which means high coupling• Code performs compile-time ‘magic’

Why not?

Unit testing traits

• Recall traits are included with the ‘use’ keyword• Resolved and ‘flattened’ at compile-time

so cannot be replaced at runtime• Trait is therefore highly coupled to class• This in turn makes testing more difficult• Traits cannot be tested as a unit• Class making use of trait cannot be tested

in isolation

Remember the high coupling?

• Don’t abuse traits!• Favour composition over inheritance• Most of the problems traits may solve

can be better solved with other means like dependency injection, decorator design pattern and others

What to do?

• Traits are useful for simple shared functionality• Can be overused• Allow you to achieve multiple

inheritance• Are hard coded dependencies• Avoid code duplication

In closing

1. Wikipedia - http://en.wikipedia.org/wiki/Trait_(computer_programming)

2. Sebastian Bergmann (PHPUnit) - http://sebastian-bergmann.de/archives/906-Testing-Traits.html

3. ircmaxell's blog - http://blog.ircmaxell.com/2011/07/are-traits-new-eval.html

Sources

Shaun MorrowBetTech Gaming

@shaun_morrow