1

I am trying to create a PHP application using the MVC pattern. I am new to MVC and I do not use a framework since I want to understand in more depth the underlying MVC processes.I have a question regarding models, JSON representation and foreign keys. Lets assume that I have two models:

Class User {
    public $id;
    public $name;
    public $gender_id;
}

Class Gender{
   public $id;
   public $description
}

The User->gender_id is a foreign key to Genders->id table.

My URI is /users/1 which is supposed to return the following JSON:

{"id":1,"name":"john","gender":"male"}

Is the controller's duty to know the model relations and retrieve the necessary data (user & gender model) which will then be passed to a view that will output the JSON ? Or should the association be defined somehow in the User's model? The gender description is a descriptive attribute but somehow it must be included in the Users view.

Regards

Stathis
  • 41
  • 4

1 Answers1

0

It is not the controller's duty to retrieve persisted data, you should have a Mapper for that. There are many answers that explain in detail the functions of Models and Controllers (this is a very good one).

Class User
{
    private $id;
    private $name;
    private $gender;

    public function __construct($id, $name, Gender $gender)
    {
        $this->id = $id;
        $this->name = $name;
        $this->gender = $gender;
    }

    public function getId()
    {
        return $this->id;
    }
    ... and other getter/setters

    public function setGender(Gender $gender)
    {
        $this->gender = $gender;
    }

    public function getGender()
    {
        return $this->gender;
    }
}

And your gender class thus:

Class Gender
{
    private $id;
    private $description;

    public function ($id, $description)
    {
        $this->id = $id;
        $this->description = $description;
    }

    //with getters and setters
}

You can proceed to make a 'Service' (for lack of better word) to return your a JSON string of your User object. Note that this 'Service' is considered to be a part of your Model (see this)

Class UserToJSON
{
    public function convert(User $user)
    {
        $user_arr = array();
        $user_arr['id'] = $user->id;
        $user_arr['name'] = $user->name;
        $user_arr['gender'] = $user->gender->getDescription();
        return json_encode($user_arr, true);
    }
}

With all this in place (assuming you have a valid User object), you can get your JSON for a user easily like so:

$user = new User(1, "name", new Gender(1, "female"));
print (new UserToJSON())->convert($user);
Community
  • 1
  • 1
IROEGBU
  • 948
  • 16
  • 33