• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Refactoring controllers. :/

#2
[eluser]TWP Marketing[/eluser]
pluus
I've edited your controller to add a generic display method at the bottom, The other methods setup the data array and call the display method. I also added return; to some of them. The concept is called DRY - Don't Repeat Yourself

[quote author="pluus" date="1344356577"]
Code:
<?php
class News extends CI_Controller {

public function __construct()
{
  parent::__construct();
  $this->load->model('news_model');
}

public function index()
{
  $data['news'] = $this->news_model->get_news();
  $data['title'] = 'News archive';
  $data['view_path'] = 'news/index'; // this is the view to be shown as content
  $this->show_page($data); // this will display your page
  return;
}

public function view($slug)
{
  $data['news_item'] = $this->news_model->get_news($slug);

  if (empty($data['news_item']))
  {
   show_404();
  }

  $data['title'] = $data['news_item']['title'];
  $data['view_path'] = 'news/view'; // this is the view to be shown as content
  $this->show_page($data); // this will display your page
  return;
}

public function create()
{
  $this->load->helper('form');
  $this->load->library('form_validation');
  $data['title'] = 'Create a news item';
  $this->form_validation->set_rules('title', 'Title', 'required');
  $this->form_validation->set_rules('text','text','required');

  if($this->form_validation->run() === FALSE)
  {
   $data['view_path'] = 'news/create'; // this is the view to be shown as content
  }
  else
  {
   $this->news_model->set_news();
   $data['view_path'] = 'news/success'; // this is the view to be shown as content
  }
  $this->show_page($data); // this will display your page
}

public function show_page($data)
{
  $this->load->view('templates/header', $data);
  $this->load->view($data['view_path'], $data);
  $this->load->view('templates/footer');
  return;
}

}?>

...[/quote]


Messages In This Thread
Refactoring controllers. :/ - by El Forum - 08-07-2012, 09:22 AM
Refactoring controllers. :/ - by El Forum - 08-07-2012, 10:01 AM
Refactoring controllers. :/ - by El Forum - 08-07-2012, 10:42 AM

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.