Last active
August 29, 2015 14:02
-
-
Save fesor/364d8fa71f6ea34e5e4a to your computer and use it in GitHub Desktop.
Bad and good examples of traits
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 | |
trait Serialization | |
{ | |
protected function serialize($data, $groups = null) | |
{ | |
$context = new SerializationContext($groups); | |
return $this->serializer->serialize($data, $context); | |
} | |
} | |
class ControllerWithTrait | |
{ | |
use Serialization; | |
protected $serializer; | |
public function __construct(Serializer $serializer) | |
{ | |
$this->serializer = $serializer; | |
} | |
public function withTraits() | |
{ | |
$data = ['some', 'data']; | |
return $this->serialize($data, 'my_group'); | |
} | |
} |
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 | |
class Controller | |
{ | |
protected $serializer; | |
public function __construct(Serializer $serializer) | |
{ | |
$this->serializer = $serializer; | |
} | |
public function withoutTraits() | |
{ | |
$data = ['some', 'data']; | |
$context = new SerializationContext('my_group'); | |
return $this->serializer->serialize($data, $context); | |
} | |
} |
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 | |
class SerializerContext | |
{ | |
private $serializationGroups = []; | |
public function __construct($groups = null) | |
{ | |
$groups = is_null($groups) ? 'default' : $groups; | |
$groups = is_array($groups) ? $groups : [$groups]; | |
$this->serializationGroups = $groups; | |
} | |
} | |
class Serializer | |
{ | |
// ... | |
public function serialize($data, $context) | |
{ | |
// do something with data. Context stores settings for our work | |
} | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment