Last active
October 2, 2015 19:58
-
-
Save bluefuton/2310100 to your computer and use it in GitHub Desktop.
PHP 5.4: sluggable trait example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* Traits: you can probably think of them a bit like interfaces, | |
but instead of just defining a list of methods that need to be implemented, | |
they will actually be implemented by including the trait. | |
Known in Ruby as mixins. | |
The name was inspired by Steve's Ice Cream Parlor in Somerville, Massachusetts: | |
The ice cream shop owner offered a basic flavor of ice cream | |
(vanilla, chocolate, etc.) and blended in a combination of extra items | |
(nuts, cookies, fudge, etc.) and called the item a "Mix-in", | |
his own trademarked term at the time. | |
.-"`'"-. | |
/ \ | |
| | | |
/'---'--`\ | |
| | | |
\_.--._.-._/ | |
\=-=-=-/ | |
\=-=-/ | |
\=-/ | |
\/ | |
*/ | |
// You can't do multiple inheritance with extends | |
class MapMarker extends ActiveRecord, Sluggable | |
{ | |
} | |
// You can't define the actual implementation of methods using interfaces | |
interface Sluggable | |
{ | |
public function get_slug() { }; | |
} | |
// You could add a base class with some common functionality, | |
// but this could get bloated pretty quickly... | |
class SuperDuperActiveRecordWithSprinkles extends ActiveRecord | |
{ | |
public function get_slug() | |
{ | |
return StringExtensions::to_slug($this->name); | |
} | |
} | |
class MapMarker extends SuperDuperActiveRecordWithSprinkles | |
{ | |
} | |
// ... SuperDuperActiveRecordWithSprinkles can keep gathering | |
// unrelated methods that aren't frequently used | |
// Traits to the rescue! | |
trait Sluggable | |
{ | |
public function get_slug() | |
{ | |
return StringExtensions::to_slug($this->name); | |
} | |
} | |
class MapMarker extends ActiveRecord | |
{ | |
use Sluggable; | |
} | |
$map_marker = new MapMarker(); | |
$map_marker->name = 'Doodle Bar'; | |
echo $map_marker->get_slug(); | |
>> doodle-bar | |
// More examples of clever things you can use mixins/traits for: | |
// http://stackoverflow.com/a/355675/233883 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment