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条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划