Question

Context

I have objects that I want to insert in a MySQL database and because I don't want to go through all the DB Management using plain code with PDO, I decided to give a try to RedBean PHP ORM.

Below are 2 of my objects:

class Profile {
  public $Name;
  public $Description;
  public $Disabled;
  public $ListOfProfileTranslation;
}

class ProfileTranslation {
  public $LanguageCode;
  public $Title;
  public $Description;
}

The 2 objects above are somehow "linked" in the sense that Profile's ListOfProfileTranslation hold an array of "ProfileTranslation"

Execution and RedBean PHP

I know that RedBean PHP can help in the way that it simplifies CRUD operations on the DB; I've also seen examples like on RedBeanPHP to declare tables and every column independantly but I thought maybe RedBean PHP could show me some additional magic and handle it on its own if I passed it an object (because table name, column names and values so I was guessing that RedBean PHP could handle it on its own in some way but I may be mistaken).

So that I could maybe write something like :

    $Profile = R::dispense('Profile');
    $Profile = $itemObject; // where $itemObject is a "Profile" object 
//which already exists in memory
    R::store($Profile);

I know that the above would raise exceptions and won't execute but is there some way to go this far in database management simplification?

OR

Do I have to go through all the steps like :

$Profile = R::dispense('Profile');

$Profile->Name = $itemObject->Name;
$Profile->Description = $itemObject->Description;
$Profile->Disabled = $itemObject->Disabled;

R::store($Profile);

What would the best solution for implementing those 2 objects and link them in DB with RedBean PHP would be according to you?

Was it helpful?

Solution

Given a $profile and a $translation, you can link them like this:

$profile->ownTranslation[] = $translation;
R::store($profile);

Now RedBeanPHP will connect the translations to the profile. As for the classes, the idea is you don't need these. Imagine you have this ProfileTranslation class, how would you set the properties? Using setters?

$profTrans->setLanguageCode($lang);

Then, why not set them directly, we all know setters don't do a lot of useful stuff anyway.

$profTrans->language = $lang;

If you need some kind of validation you can add this to a class, however there is no need to redeclare properties in the class, write accessors etc. The two are 'fused' automatically by RedBeanPHP:

 class Model_Translation extends RedBean_SimpleModel {

     public function update() {
        ...validate here, just throw exception if anything is wrong...
     }

 }

And... you're done. No need for property declarations, no need for accessors, getters, setters... just done.

That's the power of RedBeanPHP.

Cheers, Gabor

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top