API model classes - best way?


This is a question of "good practice" on implementing OO design.

I have CActiveRecord model classes, that I want to make available through json for writing API GET methods (no SOAP needed, just returning data).

The question is, how to do it the right OO way. Example:

I have a class models/Shop.php (CActiveRecord) that has fields: id, name, content, created_at, updated_at.

Now, for the API, I want to return in JSON only the name, content and created_at fields.

What I am doing now, is:

$apiObject = $activeRecordObject->getAttributes();


return json_encode($apiObject);

but I think this is not how it should be done. I thought about doing a "model" class like ShopAPI that defines only the public attributes I want, and then doing:

$apiObject = (ShopAPI) $activeRecordObject;

but maybe you have other good practice solutions for doing such an API?

Your code can be simplified a bit:

return json_encode($activeRecordObject->getAttributes(array('name', 'content', 'created_at'));

I don’t think it’s worth creating a new class for this purpose (unless you are a Java developer :) ).

Indeed, that’s a good solution, I missed out that I can pass array of names of attrs to the getAttributes() method.

But still, yes, I am a JAVA developer and this is not a clean solution.

Moreover, sometimes I have more attributes that I want to set that are not inside the database model.

That’s why I am disconnecting the API classes from CActiveRecord classes… :slight_smile:

This might be a good read for REST API best practice in Yii…

REST API with Yii