Overriding models with gii pattern

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

Yes, but Yii is better than those other frameworks :)

You can either use Yii2 Gii Extented directly or make a Gii extension of your own that does exactly what you need it to.

Check out the section on Gii in the Guide if you want to learn how it works and how it can be extended.

I remember that in Yii 1.x was a plugin doing that stuff for you, but I’m not sure that it exists in Yii 2.x. I’m also extending base models once when I generate them using Gii, but when I regenerate them again, I use replace functionality in my IDE to quickly change class names used in related-functions (I need about 1 min to do it).

I will let you know if I find something which fits your needs

Well, I already wrote about Yii2 Gii Extended - it does exactly that.

But, in my opinion, the best way is to write one yourself. Take the model template from GIIX as a starting point.

If you spend 10 minutes on that, you don’t have to manually change things around whenever you run Gii again.

Cool, thx for sharing :)