tags:

views:

58

answers:

4

Hi, I'm after a model-based database class for PHP/MySQL. But it must have one particular functionality:

Once the class is initialised ( e.g $user=new User(); ) I should be able to access the attributes in the user table as follows:

$user->name // returns the value of the 'name' field in the user table

I should not have to define the attributes or need to create any functions to return the attribute value, it should be done automatically when the class is initialised.

Is there such a database class out there? If not can someone tell me how I would go about creating this functionality?

+2  A: 

I am unsure on a database class, but if you were to write one then look into PHP's Magic Methods, in particular the __get() function

http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

class myClass {

    function __get($field) {
        // grab $field from database
    }

    function __set($field, value) {
        // set $field in database
    }
}

$class = new myClass();

echo $class->field1; // grab value field1

$class->field1 = 'myVal'; // set field1 = 'myVal';
Lizard
This looks good. But I assume I would still need to manually define the field names? I want complete automation, so for example if I were to add a new field to the database I should just be able to access it without adding any new code.I suppose what's needed is for the class needs to go in to the table, get the list of field names and add them as properties of the object.
GSTAR
A: 

You can use stdClass to do just that:

$object = new StdClass;  
$object->foo = 'bar'; 

Or if you want a little bit more control you could use PHP's magic methods.

Manos Dilaverakis
+1  A: 

Check out http://www.phpobjectgenerator.com/. Will same you a lot of time in the long run.

gnome
+1  A: 

Have you looked at Doctrine? You can generate model classes based on your DB schema. I use it on every project and I love it.

Arms
I had a look at Doctrine but I can't make any sense of it. Have you got any usage examples for finder and crud functions?Also did you get version 1.2 stable or 2.0 beta?
GSTAR
Anybody else used Doctrine? How easy is it to use?
GSTAR