April 16, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Fat Models and Skinny Controllers Bring Out the Best in Your MVC Framework, Page 2

  • January 4, 2010
  • By Jason Gilmore
  • Send Email »
  • More Articles »

Beefing Up the Model

We'll start by moving the model logic completely into the Book model. What's more, we'll consolidate both the insertion and modification tasks within a single class method named save(). This method will take care of the data validation for both tasks, and based upon whether a book ID was included in the POSTed contents, will either execute the Zend_Db's insert() or update() method:

function save($entry) {
 
  // Define a message array
  $this->messages = array();
 
  // Title
  if (! Zend_Validate::is($entry['title'], 'NotEmpty')) {
    $this->messages[] = "Please provide a book title.";
  }           
 
  // Author
  if (! Zend_Validate::is($entry['author'], 'NotEmpty')) {
    $this->messages[] = "Please provide the author name.";
  }           
 
  // If no errors, insert entry into database
  if (count($this->messages) == 0) {
 
    // Modify an existing entry
    if (isset($entry['book-id'])) {
 
      $book = $this->find($entry['book-id'])->current();
 
      $data = array (
        'title'        => $entry['title'],
        'title'        => $entry['author']   
      );               
 
      $where = $this->getAdapter()->quoteInto('id = ?', $entry['book-id']);
      $id = $this->update($data, $where);
 
      if ($id) {
       return $id;        
      } else {
       $this->messages[] = "The book could not be updated.";
       return $this->messages;
      }               
 
    // Insert a new entry
    } else {
 
      $data = array (
        'title' => $entry['title'],
        'author' => $entry['author']   
      );               
 
      $id = $this->insert($data);
 
      if ($id) {
       return TRUE;        
      } else {
       $this->messages[] = "The book could not be added.";
       return $this->messages;
      }               
 
    }
 
  } else {
    return $this->messages;
  }
 
}

With the data logic moved into the model, the add() and edit() actions can be significantly reduced in size:

public function addAction()
{
 
  if ($this->getRequest()->isPost()) {
 
    $book = new Default_Model_Book();
 
    $result = $book->save($_POST);
   
    if (is_array($result)) {
      $this->view->messages = $result;
    } else {
      $this->view->messages[] = "The book has been added.";
    }
 
  }
   
}
 
public function editAction()
{
 
  $book = new Default_Model_Book();
  
  if ($this->getRequest()->isPost()) {
 
    $result = $book->save($_POST);
   
    if (is_array($result)) {
      $this->view->messages = $result;
    } else {
      $this->view->messages[] = "The book has been modified.";
    }
   
  }
   
}

An added bonus of this approach is you can greatly reduce the amount of coding time involved in creating CRUD operations because, for instance, now you can create the edit() method by simply copying your add() action, rename the copied version as edit(), and slightly modify the return message. In fact, with a bit of clever programming you could reduce the add and edit tasks down to a single action. I'll leave this task to you but invite you to e-mail me with your ideas!

Fat Models, Skinny Controllers, and Better Code

Fully embracing the MVC pattern by maintaining cleanly separated model and controller logic can go a long way towards producing cleaner, more maintainable code. Try employing this approach in your next project and I guarantee you'll be satisfied by the outcome!

About the Author

Jason Gilmore is founder of EasyPHPWebsites.com, and author of the popular book, "Easy PHP Websites with the Zend Framework". Formerly Apress' open source editor, Jason fostered the development of more than 60 books, along the way helping to transform their open source line into one of the industry’s most respected publishing programs. Over the years he's authored several other books, including the best-selling Beginning PHP and MySQL: From Novice to Professional (currently in its third edition), Beginning PHP and PostgreSQL: From Novice to Professional, and Beginning PHP and Oracle: From Novice to Professional.

Jason is a cofounder and speaker chair of CodeMash, a nonprofit organization tasked with hosting an annual namesake developer’s conference, and was a member of the 2008 MySQL Conference speaker selection board.

Jason has published more than 100 tutorials and articles within prominent publications such as Developer.com, Linux Magazine, and TechTarget.





Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel