Taylor Otwell: Controller "Thin" dan Model "Fat"

Laravel

Creator Laravel "Taylor Otwell" dalam podcast episode 11 menyinggung tentang logika kode di Controller dan Model.

Berikut quote Omm Taylor terkait controller yang ramping dan model yang gemuk:

I tend to prefer a “fat” Model approach. My Controllers are actually pretty skinny, I find.

I think DHH (David Heinemeier Hansson), who created Ruby on Rails, had a blog post years ago about how he likes to use only the “resource” verbs on Controllers and that he doesn’t like any other actions. So, when you have a Controller, you limit yourself to only index/show/store/update/delete, and if you need any other actions – usually that’s an indicator that you can extract the whole other Controller that follows those resource verbs conventions. 

So I follow that pretty strictly, which, I find, makes my Controllers pretty thin, and then I would have pretty beefy Models that have pretty rich logic on them. 

I think one misconception of this approach is that just because your Model has quite a bit of logic exposed in its public API, that doesn’t mean that all the code to perform those tasks has to be within the Model. 

So, take Forge for example, just assume a hypothetical Site Model, that has a deploy() method. Of course, sticking the entirety of the deployment logic within the Site Model is probably not even possible, for starters, and probably wouldn’t be a good idea, cause it would be quite a bit of logic. But, what you could do, is still have that public method on the Site Model, but have that call another method, or another Service, or fire off some Command or Queue Job, to actually perform the task. 

So, the Model is not necessarily “fat” in terms of lines of code, but it just has a rich API of public methods that give you a fluent nice interface, that is very readable. It’s very readable to have Site deploy(), even if behind the scenes it’s firing off other things. It keeps the public API really nice.

 Pendekatan ini sepertinya menarik, tetapi secara pribadi saya belum menerapkan sepenuhnya metode ini. Masih banyak code di controller.

Kebanyakan dari kita tentu menulis code di model hanyak untuk relasi, dll yang berhubungan dengan kebutuhan eloquent. Tetapi bapak Laravel memberi isyarat bahwa kita di berikan keleluasaan dan sangat disarankan untuk membuat model jadi lebih banyak code ketimbang controller.

Bagaimana menurut teman-teman? Lebih banyak nulis di controller atau model?


Artikel Terkait

;