Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Traits in PHP

Traits in PHP

The sildes for a talk I gave at a PHP meet up in Cape Town.
The slides cover the what where why and how of traits, and their implementation in PHP

Shaun Morrow

March 13, 2014
Tweet

More Decks by Shaun Morrow

Other Decks in Programming

Transcript

  1. 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?
  2. 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
  3. Output is 8 Why? Methods defined in the class override

    methods in the trait Order of precedence contd.
  4. Output is 16 Message! What if two traits have the

    same method names? Multiple traits
  5. 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
  6. • 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?
  7. • Can not mock for unit testing • Which means

    high coupling • Code performs compile-time ‘magic’ Why not?
  8. • 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?
  9. • 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?
  10. • 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
  11. 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