Cache layer for MVC - Model or controller?

前端 未结 2 422
梦毁少年i
梦毁少年i 2021-02-01 22:24

I am having some second thoughts about where to implement the caching part. Where is the most appropriate place to implement it, you think?

Inside every model, or in the

相关标签:
2条回答
  • 2021-02-01 22:46

    Caching should be done in the model. If I had to choose in general, I would probably end up transparently caching the model's database interaction, which wouldn't require you to make any changes to the rest of your code. This of course would be done in the parent class of your models.

    Definitely focus on caching your database query results, as interfacing with your database is where you will see the most overhead. I would argue that it would be more efficient to cache your database results (or maybe your entire initialized model) more than anything else.

    Remember that you can serialize your objects before caching, so sending complex types (arrays or objects) into memcache shouldn't be a problem. PHP 5 provides the magic methods __sleep() and __wakeup() for the very purposes of seralizing and reconstructing your serialized objects. Caching full objects in PHP is basically a piece of cake. See http://php.net/manual/en/language.oop5.magic.php for more info.

    Whether you decide to cache just your data or your entire model shortly after initialization is up to you.

    0 讨论(0)
  • 2021-02-01 22:54

    I would keep my caching responsibilities firmly within the model. It is none of the controller's or view's business where the model is getting data. All they care about is that when data is requested, data is provided - this is how the MVC paradigm is supposed to work.

    Abstract your mem_cache functionality into the parent model class. It will cut down on the amount of code you need to write (code = time = money), simplify modifications to the system, and eliminate the number of bugs you produce per model that you build (see previous formula).

    Standardize, standardize.

    0 讨论(0)
提交回复
热议问题