Reputation: 654
I am looking for a way to autogenerate classes. For example, at the moment each of my classes is defined in a separate file like this;
class book{
public $name;
public $isbn;
public $id;
}
Then I also have a data class for each class. The data class inherits a data mapper which works quite well. So if I wanted to load a book with $id = 2, I would do the following:
$bookData = new bookData;
$book = $bookData->find(2);
$book would be an initialed version of the book class and have all its properties set as they were in corresponding DB.
Now, what I have done is made use of __autoload( $className ) to automatically include my class files. I want to make it so that I don't have to create class files.
At the moment this is what I've come up with:
__autoload( $className ){
if( file_exists('classes/'.$className.'.php') ){
include 'classes/'.$className.'.php';
}else{
//Go to DB, find table with $className and Get all column names
//Use fopen() to create a new file (like the book class file above)
//Use the coloumns from DB as vars for this new file..
//fclose() file and include new file...
}
}
The above i think is quite messy though. Any suggestions as how this might be done more easily? For example using __autoload() to generate a standard class, with property names gotten from the DB and return it, without having to create a new file?
Thanks in advance
Upvotes: 1
Views: 417
Reputation: 172
I've never did that but, maybe e word you're messing for a good search is factory => class factory.
http://en.wikipedia.org/wiki/Factory_method_pattern .
Hope it helps ...
Upvotes: 0
Reputation: 33391
I don't think you need to create a new file. What you are looking for looks very similiar to "beans" in the very nice RedBean library (for ORM).
What I would do if I were you, is to not mess around with creating classes in the autoloader
. I would create a generic class called Data
.
Then you can do something like:
$bookData = new Data('book');
Then within the Data
class, you would have routines that grabs the data from the database, and applies them to the class (assuming you have an array containing data):
foreach ($data as $key => $value){
$this->$key = $value;
}
You could also set the type in the data
object:
public function __construct($type){
$this->type = $type;
}
This way, you can easily tell what "type" (or database table) that instance of the data class is refering to.
If the "book" object has special functions pertaining to "books", then you would need to create a class that extends Data
. This is inevitable, as during some point you need to insert the calculate price method somewhere:
class BookData extends Data(){
public function calculatePrice(){
//return calculated price
}
}
Another approach is to write a script that crawls your databases and generates the classes for you before hand. Obviously the downside is that you will need to run this script to regenerate the classes everytime you change your database structure.
Upvotes: 1