Php traits

ShaunMorrow 482 views 16 slides May 27, 2015
Slide 1
Slide 1 of 16
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16

About This Presentation

We examine the where, how and why of a method of code reuse available since PHP 5.4


Slide Content

Traits in PHP The 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 is 16 Message! What if two traits have the same method names? Multiple traits

insteadof operator is your friend! Output will be 16 Other 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

Wikipedia - http://en.wikipedia.org/wiki/Trait_(computer_programming) Sebastian Bergmann (PHPUnit) - http://sebastian-bergmann.de/archives/906-Testing-Traits.html ircmaxell's blog - http://blog.ircmaxell.com/2011/07/are-traits-new-eval.html Sources

Shaun Morrow BetTech Gaming @shaun_morrow