Getting database values ​​in objects

The thing is, you have classes, and then you have database data. When you create an object, how do you set the properties of objects to store data in a database?

I saw something like this and I wonder if this is really the best way to do this. I am sure this is a fairly common problem, but I do not know what are the most acceptable solutions on how to handle it.

In this example, when the object is created, you pass the identifier as a parameter, and then run a query into the database with the identifier, and you return the return values ​​to the properties of the object. I have little experience with PHP, and I have not seen this used a lot.

Is this an acceptable way to achieve this? Is there a better or more acceptable way?

public function __construct($id = null){ if($id != null){ $sql = "SELECT * FROM users WHERE user_id = $id"; $res = Db::returnRow($sql); // $res contains an associative array with database columns and values if($res){ $this->user_id = $res['user_id']; $this->user_name = $res['user_name']; //and so on... } } } 

Can someone provide sample code or pseudo-code to illustrate how to do this correctly?

+4
source share
4 answers

Perhaps this may be an acceptable way to do homework. But architecture is not.

Your class representing your business data (the user in your example) should be loosely coupled to the database access logic. After all, a PHP class acting as a user does not need to know that the data comes from a database, file, or any other resource. After that, you can reuse your user php class in other projects without having to change anything! If you have data access logic inside it, you are stuck.

Conclusion: I would suggest reading some resources on the Design Pattern (in your situation, take a look at the DAO pattern);) Hint: one of the Head First series is extremely accessible and enjoyable.

+4
source

You can create a function that does this automatically for you by going through pairs of associative arrays / values. Or you can explore the ORM library.

+2
source

Yes, you can semi-automate this if the parent class inherits all objects. When loading, it queries "SHOW FIELDS FROM [my tablename]" and populates the associative array with names. If the identifier was passed, it searches for a valid object in this table with this identifier and assigns values ​​to the array.

Side note: do not pass your identifier directly to your request. Parameterize sql and wrap the function around any user input to sanitize it.

+1
source

If it is mysql, you can simply do:

 $obj = mysql_fetch_object($query); 

PDO is the ability to use arbitrary classes as the target for fetching, but be careful to assign variable data before running the constructor:

 $pdo->query($stmt, PDO::FETCH_CLASS, "MyClass", array('foo'=>'bar')); 

... where the final parameter contains the arguments for your class constructor.

0
source

All Articles