DEV Community

loading...

The single most usefull php trait I use in my projects

sadick profile image Sadick ・Updated on ・1 min read

I use this very often to convert a class to array and json. I thought I should post it here, it may help someone. πŸ˜€

trait Serializer
{
    public function toArray()
    {
        return get_object_vars($this);
    }
    public function toJSON()
    {
        return json_encode($this->toArray());
    }
}
Enter fullscreen mode Exit fullscreen mode

How to use it.

Assuming you have a model of Person and would like to access it somewhere in your code as an array or json.

class Person
{
    use Serializer;
    private $id;
    private $name;
    public function setName($name)
    {
        $this->name = $name;
    }
}

$person = new Person();
$person->setName("Isaac");

$arr = $person->toArray();
print_r($arr);

$json = $person->toJSON();
print_r($json);
Enter fullscreen mode Exit fullscreen mode

I find this very convenient while developing rest api's.

Discussion (4)

pic
Editor guide
Collapse
daniel15 profile image
Daniel Lo Nigro

You should implement the JsonSerializable interface (secure.php.net/manual/en/jsonseria...), then you can just pass your object to json_encode() and it'll do the right thing. That'll also handle JSON serializing an array of them, without having to serialize each one manually (just serialize the array and it'll call the jsonSerialize method on each one).

Collapse
sadick profile image
Sadick Author

Yah sure, but the downside of implementing JsonSerializable is that i will need a different return value to jsonSerialize in all of my models because i have to construct an array representation of the class every time.

class Person implements \JsonSerializable
{
    private $id;
    private $name;
    public function setName($name)
    {
        $this->name = $name;
    }
    public function jsonSerialize()
    {
        return [
            'id' => $this->$id,
            'name' => $this->name,
        ];
    }
}
Collapse
daniel15 profile image
Daniel Lo Nigro

Good point. I forgot that traits can't implement interfaces in PHP. I use Hack at work, which is based on PHP but traits are able to implement interfaces when using Hack.

Collapse
perttisoomann profile image
Pert Soomann

Very neat truck, cheers for sharing.