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

Trait とは? その使い道を考えてみる

Trait とは? その使い道を考えてみる

2012/09 の社内 LT で発表した資料

Takuya Fujimura

September 07, 2012
Tweet

More Decks by Takuya Fujimura

Other Decks in Technology

Transcript

  1. ࣗݾ঺հ • ౻ଜ ୓໵@tlync • ΞϓϦέʔγϣϯ։ൃୈೋ • ࠷ۙͷؔ৺ࣄ • Scala,

    Agile(Project Mgt.) • PHP ͸ੜ͖Δҝʹ΍͍ͬͯ·͢ 12೥8݄9೔໦༵೔
  2. ଞݴޠͰͷྨࣅͷػߏ • Scala … trait • Perl 6 … role

    • Ruby … Mix-in ※ಉ༷ͷ֓೦͕ͩ࢓༷͸ඍົʹҟͳΔɻ ܕ৘ใΛ͔࣋ͭ(is_aΛύε͢Δ͔)ͱ͔ɻ 12೥8݄9೔໦༵೔
  3. trait Engine { public function startEngine() { echo 'BRRRM!'; }

    } class Car { use Engine; } (new Car)->startEngine(); // BRRRM! 12೥8݄9೔໦༵೔
  4. class Vehicle { protected function startEngine() { echo '⚡'; }

    } class Plane extends Vehicle { public function fly() { echo '✈'; } } class Boat extends Vehicle { public function sail() { echo '⚓'; } } 12೥8݄9೔໦༵೔
  5. interface Plane { public function fly(); } interface Boat {

    public function sail(); } 12೥8݄9೔໦༵೔
  6. class SimplePlane extends Vehicle implements Plane { public function fly()

    { echo '✈'; } } class SimpleBoat extends Vehicle implements Boat { public function sail() { echo '⚓'; } } 12೥8݄9೔໦༵೔
  7. class SeaPlane extends Vehicle implements Plane, Boat { private $boat;

    private $plane; public function __constract() { $this->boat = new SimpleBoat(); $this->plane = new SimplePlane(); } public function sail() { return $this->boat->sail(); } public function fly() { return $this->plane->fly(); } } $seaPlane = new SeaPlane(); $seaPlane->sail(); // ! $seaPlane->fly(); // ✈ 12೥8݄9೔໦༵೔
  8. // ໋໊͸ͪΐͬͱඍົ trait FlyEngine { public function fly() { echo

    '✈'; } } trait FloatEngine { public function sail() { echo '⚓'; } } class SeaPlane implements Plane, Boat // ܕͷܧঝ { use FloatEngine, FlyEngine; // ࣮૷ͷܧঝ } $seaPlane = new SeaPlane(); $seaPlane->sail(); // ! $seaPlane->fly(); // ✈ 12೥8݄9೔໦༵೔
  9. startEngine() Vehicle sail() Boat fly() Plane sail() fly() SeaPlane sail()

    BoatEngine fly() FlyEngine sail() BoatEngine fly() FlyEngine 12೥8݄9೔໦༵೔
  10. ܕͷอূ … Interface ࣮૷ͷ࠶ར༻ … trait ※ ஫: Scala, Ruby

    ͳͲͰ͸·ͨͪΐͬͱҧ͏Α! 12೥8݄9೔໦༵೔
  11. trait Timestampable { private $createdAt; private $updatedAt; ... getter, setter

    /** * Updates createdAt and updatedAt timestamps. */ public function updateTimestamps() { if (null === $this->createdAt) { $this->createdAt = new \DateTime('now'); } $this->updatedAt = new \DateTime('now'); } } 12೥8݄9೔໦༵೔
  12. /** * ঎඼ΤϯςΟςΟ */ class Product { use Timestampable, //

    λΠϜελϯϓΛࣗಈͰ SoftDeletable, // ιϑτσϦʔτՄೳʹ Activatable; // ׆ੑɺඇ׆ੑΛՄೳʹ private $name; // ຊ࣭తͳϩδοΫ } 12೥8݄9೔໦༵೔