Polymorphic associations

As is proven by experience, polymorphic associations are handy at making pluggable webapp modules. Yii comes with out-of-box modules’ support but their use seems to be somehow restricted.

That’s not an actual problem but a large collection of ready-to-use modules would essentially contribute to further success of Yii.

Imagine this situation: We have a pluggable comments module. It has ActsAsCommentable behavior and CommentsAction as an extension (and of course, all the necessary controllers, models and views). The Comment models has in its relations something like


'commentable'=>array(Generic::BELONGS_TO, 'commentable_type', ...)

In the extension’s CommentAction class, the commentable_type could be derived from the current controller name.

What is the benefit?

We could make commentable any model in the host webapp by adding ActsAsCommentable behavior to the model in question and by adding CommentsAction to the correposnding controller’s actions array. The ActsAsCommentable would care about adding the required relationship, in the OnAfterCreateEvent, to the metadata of the host model:


'comments'=>array(Generic::HAS_MANY, 'commentable_type', ...)

Note that the host model’s table doesn’t need to know anything about the plugin’s tables; but the model of the plugin must have an extra column to store the type(i.e., name) of the polymorphic relationship.

True, this feature can be implemented as an extension (see, e.g., this), but adding it to the core would yield many reusable modules in the repository.

I’d like to second this request. I’m working with a few models that can have comments, but cannot easily determine the “parent” model of the comment without a custom query. Thanks!

+1 on this.

I’ve just found my first, real use for Polymorphic associations, but it’s not available on Yii yet, AFAIK :confused:

I second this - it would be a very useful way of reusing code.