dongyue1988 2012-02-26 06:08
浏览 49
已采纳

PHP OOP保存,将类属性获取到数据库

I'm trying to learn oop. I'm working with PHP-MySQL. And I have troubles about database jobs with oop way (save, update, get etc.).

Let me explain it with an example project.

Lets say I want to make a site with multiple user types. I have a single database table with an enum "type" field. And I made classes like these:

abstract class User {
 //common properties, functions etc.. like id, username.
}

class Admin extends User {
 protected $type = "ADMIN";
 //I want here to have admin specific fields, functions etc...
}

...and some other user types like that. Here is the thing. I want a common class that can save and update objects into database. What's the way to do that? I'll make an object like $user = new User(); bla.. bla.. and I'll say "Save this user" but how? Do I have to make functions for each of my classes that have specific SQL statements like "INSERT INTO table(name, pass, etc) VALUES ('name', 'pass', etc)"?

Another point is I want a common factory class that returns me an object. An example I'll say "Get me the user which have this id and instantiate it with admin class if that user is an admin or the other classes like that".

And I need some help about "how to instantiate like mysqli_fetch_assoc() result with objects". That returns an array. Do I need to do like "$object->setId(returned_array["id"])"?

I've looked some books like PHP in Action, PHP Objects, Patterns and Practice but couldn't find this database specific topics. I hope I could explained it well and sorry for my bad English :)

  • 写回答

2条回答 默认 最新

  • duandu8202 2012-02-26 07:31
    关注

    I think you need an ORM framework. It's hard to create a good one on your own but you can find a few existing frameworks. Be carefulf do not use a framework with active record pattern becouse it's an antipattern.

    To fetch objects: http://www.php.net/manual/en/mysqli-result.fetch-object.php

    But I also recommend you to use mysqli in OO way:

    $resource = new mysqli(/* ... */);
    $resource->fetch_object(/* ... */)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历