I’m using gii to generate models from the database, but I place them in the app\models\db namespace. I then create empty classes in app\models namespace that have the same name and extend the app\models\db models.
This makes it really powerfull since I can create additional functions in the empty classes in the app\models namespace without worrying that those get removed when I update my DB and re-run gii to update the models.
The only problem is that the auto-generated relation-functions (getUsers for example) return an object in the app\models\db namespace, so I can’t use my additional functions on that.
Example:
user ----< message
I have a table user and message. A user can have multiple messages. Foreign keys are made. The message model is extended with an additional function (in the app\models namespace).
Gii will generate a getMessages() in the User class, what is great. Except, when I have the following code, it will not work.
<?php
$user = User::findOne(1);
$messages = $user->getMessages();
foreach ($messages as $message) {
$message->doMyNewFunction();
}
The messages will be an array of Message objects from the app\models\db namespace, and they don’t contain my changes.
One way to solve this is to copy all the relation-function from the gii-models to my overridden models, so they will be executed in the context of my app\models classes instead of the app\models\db classes.
Unfortunatly, this forces me to copy all the relation functions everytime, and I was wondering if there is a better solution for this. Some other frameworks have this functionality build-in (their codegen makes the empty classes itself, and they always use these classes when objects are created).