duanju9104 2015-08-27 02:46
浏览 57
已采纳

Laravel 5拆分模型

PHP noob here.

I have an Item model which is responsible for adding items to my cart.. However the items I'm adding are not simple products. Each item type has a complicated formula for generating a customized quote based on the users selections and personal discount, etc.

The simplest way I can think to do this is to have functions for each product within the item model with each unique formula in. However, this will get messy very fast.

What is the best practice for splitting these into separate files and then including those files in the model, just for keeping my code clean and seperate?

So for example I have aircraft, cars, boats as categories, each product within each category has it's own formula but I at least want to keep aircraft formulas separate from boat for ease of reading.

Is it best to create an aircraft model, boats model etc and have them all use the items DB table and then once they are added I can control them all from the Item model?

I may have just answered my own question, but I don't know :D Learning loads but still a noob.

  • 写回答

1条回答 默认 最新

  • dongqian6234 2015-08-27 05:10
    关注

    I would suggest two things:

    Extract logic from models

    I would extract as much of the business logic as possible from the models - to, say, several formula classes (one for each different formula), which you can easily execute wherever you need to.

    If the data you will save differs between each type, you may want to look into...

    Polymorphic relationships

    See the laravel docs on this for specifics.

    You would have a Product model, that has a polymorphic morphTo relationship (called "type", maybe) to several other "product type" models (that all have an inverse morphOne back to the Product).

    Polymorphic relationships were the first thing i thought of while reading your question, but on re-reading it, the data structure for each type might not be different. If that's the case, ignore the polymorphic bit!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部