3

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?

Community
  • 1
  • 1
Highmastdon
  • 6,960
  • 7
  • 40
  • 68

1 Answers1

0

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...

Doc Roms
  • 3,288
  • 1
  • 20
  • 37
  • Yes, but this isn't what I mean. It's more like I don't know a good structure to put the database connections in. So regarding the question: Where should i put the 'load' part of the user and the serialization to the User-object? – Highmastdon Aug 23 '12 at 10:07