… another topic slowly entered my brain…
Why do we love CakePHP so much? (And why do others equally hate it for the same reason?)
Here’s what our dear wikipedia had to say about this:
Convention over Configuration (aka Coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility.
In other words, for those who are lazy, like me, Convention over Configuration can make life so much easier and all one has to do in exchange is to follow a few simple rules (AKA conventions).
So let’s take a look at a practical (albeit a very simple) example of how Convention over Configuration can make your code do all… those nice things that wikipedia talks about.
Without wasting anymore time, let’s take a look at this tiny code snippet that I often use in my views:
If you haven’t read the previous posts, let me briefly explain what’s happening. In using jQuery many of my pages require view or page-specific jQuery files to be loaded.
Now that’s all nice and well… but whoa… seems like a lot of typing to me. No?
Wouldn’t it be nicer if I could just do:
And it would automagically load the appropriate jQuery file for the given page?
Well, you’ve probably noticed that I do use a Convention in the way I name the JS files:
1. Controller name = “beers”
3. Action name = “view_beer”
Following this convention I can write a tiny helper that will handle the file includes for me, rather than me having to type out an entire path (oh no!).
So, let’s make the little helper js_manager.php (in our app/views/helpers directory):
And that’s all there is to it.
Whenever I use $jsManager->myJs();, the helper will find and include the file based on the Convention specified by the three simple rules listed above. I hope the code is simple enough so that you can see exactly how it works.
Of course, I did a lot more typing by writing a helper… but if I’ve got an app with 700 views, it might come in quite handy in the long run. Not to mention, if for whatever reason I decide to change the ‘page_specific’ path name to something else, the change will be a lot easier to handle.
Granted this is a very simple example, but I hope it provides some insight as to why so many developers have embraced the Convention over Configuration paradigm.
And to summarize: learn the conventions (or make your own) and in the long run make your life easier (just like wikipedia promised)!