As I mentioned in my first post, when I started using Laravel I knew nothing about the concept of MVC. It was difficult to transition from writing pure PHP (which I had only learned 6 months prior to working with Laravel) to an MVC framework. There a lot of great resources for MVC noobs —tut+’s MVC for Noobs is one—and introductions to Laravel—Laracast’s free Laravel From Scratch series is one, Laravel Book’s Architecture of Laravel Applications (http://laravelbook.com/laravel-architecture/) is another—but let’s quickly recap the basic concepts.
The MVC Pattern
At its core, the MVC architectural pattern exists to help with the Separation of Concerns (https://en.wikipedia.org/wiki/Separation_of_concerns) in your code. The MVC pattern consists of:
- Models: represent stored data and enforce “business” rules/logic on the data (in Laravel, a model is analogous to a table in your database)
- Views: present data to the user
- Controllers: mediate between the View and the Model
In Laravel 4, the app directory has folders for controllers, models, and views. You would expect the typical flow of information would go like this:
- A route is invoked
- The route calls a function within a controller
- The controller uses a model to access data
- The controller passes that data to a view
- The view displays the data to the user
And in it’s most simplest form, that’s exactly how the Laravel framework works. Looking at the files that are included in a new Laravel install (at least in Laravel 4.x, this is changing with Laravel 5.x), this made sense. And so I moved forward believing that everything must fall into a model, a view, or a controller.
My Controllers Needs A Diet
The first feature I created for the SimpliFit beta API was simple: show all the habits a user has learned since they started with SimpliFit. We called this feature Achievements. “Easy enough,” I thought as I created a few models, coded the relationships, and seeded the database. In the end, my one controller function had ballooned to over 100 lines of code while my models were at about 30. I tested the feature and it worked.