douqipi9704 2012-08-23 07:28
浏览 399

如何在PHP中使用ORM

I've seen a dozen of topics and questions that are stating to use ORM in PHP (30 php best practices for beginners and Why use an orm in php)

So I'm wondering, HOW to use ORM with PHP. Especially OOPHP.

Let's say we've a class User and we are registering one. (I'm using RedBean)

<?php
class User {
    private $username;
    private $password;

    public function registerUser($username, $password) {
        require $root . "classes/Helper.php";
        $helper = new Helper();
        $salt = sha1($helper->generateSalt());

        $this->username = $username;
        $this->password = sha1($password + $salt);
        $this->salt = $salt;
        $this->store();
    }
    private function store() {
        $user = R::dispense(__CLASS__);
        $user->username = $this->username;
        $user->password = $this->password;
    }
}
?>

This works. Everytime a user gets registered, I'm storing it aswell. Or is it maybe better to put the store() function in the __construct() Or is there an even better way to do it? Is it usefull to use __CLASS__ or should I better use 'User'?

private function load($username){
    $user = R::find(__CLASS__, 'username=?', array($username));
    $this->username = $user->username;
    $this->password = $user->password;
    $this->salt = $user->salt;
    $this->email = $user->email;
}

Now if I want to load a user I can in my page create a new User object and call load() to fill it with the desired user. Or should I directly use $userbean = R::find('User', 'username=?', array($username)); and put it in a $user = new User();?

I'm getting a little confused by the ways in which several things can be done. Is this actually made to use with object-oriented PHP?

[edit:] So, is my approach this way in using RedBean and OOPHP right?

  • 写回答

1条回答 默认 最新

  • douci1196 2012-08-23 07:51
    关注

    that depends your ORM, in general you've a FAQ for get started with an ORM. For DOCTRINE 2 ORM, you can read this page, for PROPEL ORM you can read this page, and for redbean, tou can read that.

    I'm sorry, I don't know redbean, but, for other ORM, it's can be useful( I use Doctrine2), and we can used there with OOPHP. After start installation of ORM, receive Object when we "call" the ORM linked in your Database is more convenient to execute SQL request and make a treatment for every request...

    For user can't be like SQL or database, is more convenient since the ORM takes care of optimizing request...

    评论

报告相同问题?

悬赏问题

  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程