Home > Enterprise >  How do I send parameter's data in php when encoding into json?
How do I send parameter's data in php when encoding into json?

Time:11-24

I am making my own PHP framework that would work a bit like Laravel, and therefore I wanted a model system that would resemble that functionality. I've come into a problem though, when I want to send the model data through the controller's current route method, i have to invoke a custom "toArray()" function that converts the private attributes set by magic method __set:


    public function __set($name, $value)
    {
        $this->attributes[$name] = $value;
    }

    public function __get($name)
    {
        return isset($this->attributes[$name]) ? $this->attributes[$name] : null;
    }

However this makes a new problem. When returning a response, I have to add a "toArray()" method call on each model, if it's a collection of models.

    public function getUsers() {
        $users = User::paginate($_GET["page"] ?? 1, 10)->get();


        echo json_encode([
            "users" => $users->toArray(),
        ]);
    }

Is there a magic php method that I am missing? I want to just to be able to say

    public function getUsers() {
        $users = User::paginate($_GET["page"] ?? 1, 10)->get();


        echo json_encode([
            "users" => $users
        ]);
    }

CodePudding user response:

You're probably thinking of the JsonSerializable interface.

Implementing this interface in your class means when you call json_encode instead of the naieve object serialization, it'll call your jsonSerialize method.

The base model class in Laravel implements this builtin interface.

class Foo implements JsonSerializable {
    private $attributes = [
        'foo' => 'bar',
        'array' => [1,2,3,4],
    ];
    public function jsonSerialize() {
        return $this->attributes;
    }
}

$f = new Foo;
// prints '{"foo":"bar","array":[1,2,3,4]}'
print(json_encode($f));
  •  Tags:  
  • php
  • Related