Keeping your CakePHP Controllers Clean

K

As my office gains more and more experience with CakePHP, we are beginning to learn to build more organized web sites.  Looking back at our first few projects, I’m astonished to see how messy our controllers are!

I know the controllers are the “brain” of MVC because it pieces our data to our views, but that doesn’t mean everything should go in there.  Our original controllers would contain all of our logic, all of our data manipulation, all of our custom queries, and some additional data validation.

We are now working very hard to keep our controllers as clean and simple as possible.  My goal is to make every function in our controllers under 20 lines of code.  It might sound ambitious, but I think it is completely feasable.

Before I begin explaining my thoughts on the situation, I would love to hear what others have to say about this.

Here are my keys to keeping our CakePHP controllers nice and clean and easily readable:

  1. Put all data validation in the model
  2. Put all custom queries in the model
  3. Put any complex queries (more than a simple find(‘all’)) in the model
  4. Create a component for all logic
  5. Create a component for all data manipulation

By following the above 5 rules, it will make tracking down bugs and making simple alterations 10 times easier.  Imagine having to look through 200 lines of code to find where that error message is.  If it were in the model, it would be extremely easy to pinpoint it down and change it.

Have a problem with some logic, go right to your component and do not be convoluted by other code that is unrelated to the problem.

Below is a sample function that is under 20 lines of code and has all of the above 5 items segregated appropriately:

[code]function add() {
 // check if we are posting data
 if (!empty($this->data)) {
  // manipulate our data
  $user = $this->UserSetup->manipulateSomeData($this->data);
  
  // validate and save our data
  if ($this->User->save($user)) {
   $this->Session->setFlash(‘User successfully saved’);
   $this->redirect(‘index’);
   exit();
  } else {
   $this->Session->setFlash(‘There was an error saving your data’);
  }
  
  // get country list
  $this->set(‘countries’, $this->Country->find(‘all’));
  // get provinces based on countries
  $this->set(‘provinces’, $this->Province->getByCountryId(1));
 }
}
[/code]

Again, as mentioned early, I would love to hear your thoughts if you agree or disagree.  If you disagree, please let me know your approach.

Other useful articles

About the author

  • http://www.kebza.cz Marek Kebza

    I have same goal as you. But i got used to even simple calls to find(‘all’) hide in model as a method. Because you never know when conditions, ordering and so on will change. Then you don’t have to refractor and you are keeping all data manipulation logic hidden inside a model.

  • Jimmy Bourassa

    Great article, I must admit I feel quite similar to what you described haha!

    I’m just unsure about the component part – wouldn’t a component be handy only in a case where your logic must be widely usable and generic? I don’t see why you would write every kind of logic in the Component. Any explanation would be greatly appreciated

  • Jamie

    My reasoning would be to simply segregate the code more. The controller is the middle man for data and display, why not make it the middle man for logic as well?

  • http://cakebaker.42dh.com/ Daniel Hofstetter

    This practice is usually called “Skinny controllers, fat models” and is a best practice for writing CakePHP (resp. MVC) applications.

  • Alvaro

    Following REST architecture helps to made apps with skinny controllers and don’t think too much on how your actions have to be named.

  • Juan

    Hey man, now you are actually using MVC as it is meant to be.
    Controllers just control user input nothing else.
    The brain of the app are the models.

  • http://www.last-chaos-money.com last chaos money

    This is a great article. I’m new to blogging but still learning. Thanks for the great resource.

  • http://www.last-chaos-money.com last chaos money

    Good post,This was exactly what I needed to read today! I am sure this has relevance to many of us out there.

  • http://www.eveisk-shop.com/ eve isk

    I love it.

  • Pingback: Adult sleepover ? Dentists in LA | Summer Vacation Ebay

  • Pingback: beauty

  • Pingback: how to remove skin tags

  • Pingback: secrets 4 loss weight

  • Pingback: paladin pvp guide

  • Pingback: mage pvp

  • Pingback: remote virus removal

  • Pingback: Goozle Zone

  • Pingback: bad credit loans

  • Pingback: ania quisumbing

  • Pingback: cuban guayabera

  • Pingback: buy songs on line

  • Pingback: ultimate power profits

  • Pingback: zig zaga

  • Pingback: Personal Injury Solicitors in Manchester

  • Pingback: Motorbike Accident Claim Solicitors

  • Pingback: name badge holder

  • Pingback: ZigZag

  • Pingback: new york asian escorts

By Jamie

My Books