将 MySQL 查询转换为对象的最佳方法
我有一个用户表,其中包含一堆我想在登录用户的 mysql 查询中访问的列。最终,我希望这些列中的值形成一个 User 对象。是否有一个标准函数可以执行此操作,或者我基本上需要将查询的每个值传递到新的 User 语句中,以便将它们传递给 User 类的构造函数?
I have a user table that contains a bunch of columns that I want to access in a mysql query for the logged in user. Ultimately, I want the values in these columns to form a User object. Is there a standard function for doing this, or do I basically need to pass each value of the query into a new User statement so that they are passed to the User class's constructor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
mysql_fetch_object
mysql_fetch_object
您应该查看
mysqli_result::fetch_object
。您还可以查看 PHP 的 PDO 扩展。桌子
首先,了解你的桌子。
域对象
创建您的对象。您不需要定义任何这些字段,因为默认情况下它们将作为
public
添加到您的对象中,但对于以后可能维护您的代码的任何人来说都是清楚的;为了清晰起见定义字段。由于字段是私有的,因此访问器和修改器是必需的。查询
创建查询类。其中很多都是样板代码,可以将其提取到抽象类中。
从
user
表中获取User
对象。You should checkout
mysqli_result::fetch_object
. You could also look into PHP's PDO extension.Table
First, know your table.
Domain Object
Create your object. You do not need to define any of these fields, because they will be added to your object as
public
by default, but it is clear to anyone who may maintain your code later; to define the fields for clarity. The accessors and mutators are necessary since the fields are private.Query
Create a query class. A lot of this is boilerplate code, which can be extracted out into an abstract class.
Fetch a
User
object from theuser
table.mysql_fetch_object()
允许您指定一个类名,以便根据您的结果构造该类的实例:除非您指定与
SELECT
查询中列出的列相对应的属性及其访问修饰符,否则它们将默认为 <代码>公共。对象的构造函数在填充其属性后被调用。您想要执行的任何更改或附加任务都可以在构造函数中执行。
mysql_fetch_object()
allows you to specify a class name so instances of that class will be constructed from your results:Unless you specify the properties and their access modifiers that correspond to the columns listed in your
SELECT
query, they will default topublic
.Your object's constructor is called after populating its properties. Any changes or additional tasks you want to perform may be performed in the constructor.