Yii AR camel case getters

Friday, July 11, 2014 17:12

However the old Yii framework is still pretty good, it lacks in some features. One of this features is the active record camel case to snake case transparent transformer. If you had a database with snake case column names (which is the standard), then you would probably met the same snake case columns in your camel case PHP code. In this blog post I going to write a solution for this problem.

In this case, we have to write a completely transparent solution which won’t affect other plugins or the inner mechanism of the framework. We will achieve this goal by making getters and setters instead of overriding the __set magic methods.

The first thing we have to do is making a middle layer bitween the models and the framework. We will implement our code here, then all of the models will inherit this enchantment from this layer.

After creating this middle layer we can make our generic getters and setters using the __call magic method. But before writing it, we’ll need a few utility functions. The first function will be core utility function which will convert our camel case getters to snake case format. As this function won’t needed in the derived classes, we can make it private:

Okay, this function will transform the getter names, but we have to distinguish the relations and the columns as the relations defined in the models – probably already in camel case format. For this reason, we’ll transform the names only if it’s not a relation.

So, for the end, the whole BaseModel class will look:

No comments fo far.

Leave a Reply