doyhq66282
2014-07-31 12:43
浏览 22
已采纳

将数据从数据库获取到模型

So far I've used many objects in my applications but often if I had to for example display for example users' profiles on page I simply got 20 users from database as array using some method in my object and assigned it to view.

Now I want to create application more with models that represent real data. So for each user I should probably have User object with properties .

Here I put sample code to get users from database and to display them in PHP:

<?php

$db = new mysqli('localhost', 'root', '', 'mytest');

class User
{
    private $id;
    private $name;

    public function __construct($data)
    {
        foreach ($data as $k => $v) {
            if (property_exists($this, $k)) {
                $this->$k = $v;
            }

        }
    }
    public function show()
    {
        return $this->id . ' ' . $this->name ;
    }
}

$result = $db->query("SELECT * FROM `user` LIMIT 20");

$users = array();
while ($data = $result->fetch_object()) {
    $data->x = 10; // just to test if property isn't created
    $users[] = new User($data);
}

// displaying it on page
foreach ($users as $user) {
    echo $user->show() . "<br />";
}

Questions:

  1. Is it the way I should use data from database into model? I mean if should I create object for each record even if the only role of this object would be returning some data to view (for example even not modified by any functions as in this example). Of course I know that often data should be prepared to display or made some calculations or additional data should be retrieved from database before those data could be used to display.

  2. Is there any way to assign object properties from database simpler than using constructor with loop?

1条回答 默认 最新

相关推荐 更多相似问题