Welcome Guest, Not a member yet? Register   Sign In
Detailed Explanation of a Controller & Model?
#2

At the most basic level, if you configure no routes, the router interprets the URL as a controller name and method name (and optionally some parameters), then calls the appropriate method in the controller. The controller is then expected to do whatever is required to either process the parameter(s) or display the requested page.

CodeIgniter is extremely flexible, so you could (if you are a masochist) do everything in the controller, but there's really not much point to that. So, the controller decides to load the appropriate libraries and models to handle or retrieve the relevant data, then decides what views to load and what data to pass to those views.

There are at least two distinct methods of doing what you are describing. One is to configure a controller (or a parent controller) with a method to stitch together the template (we'll call this method render() for ease of reference), then set the various parts of the template in the controller method which handles a given URL and call the render() method to load the views and start output. The second is very similar, but involves creating a library to manage the template (so the render() method would be in the library instead of a controller). The more complicated the template-management code gets, the more likely I would be to put it in a library. However, you can always start with it in a controller, then move it to a library later (and have the controller's render() (and any related method(s)) call the library until you can refactor the other controller(s) method(s) to call the library instead).

In most cases, I would avoid using a single view. Instead, I would piece together the page from a series of views, reusing most of the views for all/most of the pages and modifying the relevant sections by loading in different views for each page. Let's start by breaking up the page you supplied into what appears to be the relevant areas you mentioned, with some minor modifications. The following would be views:

head.php:
PHP Code:
<meta content="en-us" http-equiv="Content-Language">
<
meta content="text/html; charset=windows-1252" http-equiv="Content-Type">
<
title><?php echo empty($templatePageTitle) ? 'Default Page Title' $templatePageTitle?></title>
<link rel="stylesheet" type="text/css" href="/css/main.css" media="screen" />
<link rel="stylesheet" type="text/css" href="/css/print.css" media="print" /> 

header.php:
PHP Code:
<div id="logo"><img alt="XAMPP" src="/images/logo/xampp.png"></div

topnav.php:
PHP Code:
<div id="nav" class="menu horizontal noprint">
 
   <ul>
 
       <li><a href="/">Dashboard</a></li>
 
       <li><a href="/applications.html">Applications</a></li>
 
       <li><a href="/faq.html">FAQs</a></li>
 
       <li><a href="/howto.html">HOW-TO Guides</a></li>
 
       <li><a href="/xampp/dashboard/phpinfo.php">PHPInfo</a></li>
 
   </ul>
</
div

sidenav.php:
PHP Code:
<div id="toc" class="menu noprint column">
 
   <div id="lnav1head">
 
       Utilities
    
</div>
 
   <div id="lnav1menu">
 
       <ul>
 
           <li><a href="/phpmyadmin">phpMyAdmin</a></li>
 
       </ul>
 
   </div>
 
   <div id="lnav2head">
 
       Projects
    
</div>
 
   <div id="lnav2menu">
 
       <ul>
 
           <li><a href="/xampp/dashboard/">XAMPP</a></li>
 
           <li><a href="/goldentempel/">Golden Tempel</a></li>
 
           <li><a href="/project1/">Project #1</a></li>
 
       </ul>
 
   </div>
</
div

footer.php:
PHP Code:
<div id="footer">Page created byJosh Davis.<br>&copy<a href="http://www.apachefriends.org">Apache Friends</a></div

There are two parts left: the container and the content. The content I'm going to name xampp.php. With the code I'm going to include later, you would generally name each content view after the method in the controller which displays the content, and place it in a directory named after the controller, but you could choose to load a different view for the content, if you wish.

xampp.php (I've also changed the HTML slightly):
PHP Code:
<h1>Welcome to <span class='xampp'>XAMPP</span> for Windows 5.6.11</h1>
<
p>You have successfully installed XAMPP on this systemNow you can start using ApacheMySQLPHP and other componentsYou can find more info in the<a href="/">FAQs</asection or check the <a href="/">HOW-TO Guides</a> for getting started with PHP applicationsStart the XAMPP Control Panel to check the server status.
</
p>
<
h2>Community</h2>
<
p>XAMPP has been around for more than 10 years &ndashthere is a huge community behind itYou can get involved by joining our <a href="https://community.apachefriends.org">Forums</a>, adding yourself to the <a href="https://www.apachefriends.org /community.html#mailing_list">Mailing List</a>, and liking us on <a href="https://www.facebook.com/we.are.xampp">Facebook</a>, following our exploits on <a href="https://twitter.com/apachefriends">Twitter</a>, or adding us to your <a href="https://plus.google.com/+xampp/posts">Google+</acircles.
</
p>
<
h2>Contribute to <span class='xampp'>XAMPP</spantranslation</h2>
<
p>Can you help translate XAMPP for other community membersWe need your help to translate XAMPP into different languagesWe have set up a site, <a href="https://translate.apachefriends.org/">translate.apachefriends.org</a>, where users can contribute translations.
</
p>
<
h2>Install applications on <span class='xampp'>XAMPP</spanusing Bitnami</h2>
<
p>Apache Friends and Bitnami are cooperating to make dozens of open source applications available on XAMPP, for freeBitnami-packaged applications include WordpressDrupalJoomla! and dozens of others and can be deployed with one-click installersVisit the <a href="http://bitnami.com/stack/xampp?utm_source=bitnami&amp;utm_medium=installer&amp;utm_campaign=XAMPP%2BModule">Bitnami XAMPP page</a> for details on the currently available apps.
</
p

Now the template/container includes a number of variables which we'll set in the render() method. We could opt to load the views directly in the template, but that wouldn't normally be considered a best practice. I also opted not to nest the views, as that would make the code to load all of the views a little more complicated (and it is already complicated enough for an example).

template.php:
PHP Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
 
   <?php echo $templateHead?>
</head>
<body>
    <div id="main">
        <?php echo $templateHeader?>
        <?php echo $templateTopnav?>
        <div id="columns">
            <?php echo $templateSidenav?>
            <div id="contents" class="column">
                <div id="sitecontent">
                    <?php echo $templateSiteContent?>
                </div>
            </div>
        </div>
        <?php echo $templateFooter?>
    </div>
</body>
</html> 

Now, even without the code that follows, you should be able to piece together what the output would look like by placing 'head' in $templateHead, 'header' in $templateHeader, and so on.

Next, we're going to build our base controller, which we'll call MY_Controller (because CI will automatically load that file, as long as your configured subclass_prefix is still 'MY_'). We're going to create two properties to hold the default page title and the names of the views. Then we'll create setter methods for those properties, a helper method to set our content view, and the render() method to check our values, set some defaults, if needed, and load all of the views.

MY_Controller.php:
PHP Code:
<?php

class MY_Controller extends CI_Controller
{
 
   private $templatePageTitle 'Default Page Title';
 
   private $templateViews = array(
 
       'content' => '',
 
       'footer'  => 'footer',
 
       'head'    => 'head',
 
       'header'  => 'header',
 
       'sidenav' => 'sidenav',
 
       'topnav'  => 'topnav',
 
   );

 
   public function __construct()
 
   {
 
       parent::__construct();
 
   }

 
   protected function render($data = array())
 
   {
 
       // Set the page title.
 
       if (! isset($data['templatePageTitle']) || $data['templatePageTitle'] == '') {
 
           $data['templatePageTitle'] = $this->templatePageTitle;
 
       }
 
       $this->load->vars($data);

 
       // If the view name hasn't been set, set it to the routed method.
 
       if (empty($this->templateViews['content'])) {
 
           $this->templateViews['content'] = "{$this->router->class}/{$this->router->method}";
 
       }

 
       $templateHead        $this->load->view($this->templateViews['head'], nulltrue);
 
       $templateHeader      $this->load->view($this->templateViews['header'], nulltrue);
 
       $templateTopnav      $this->load->view($this->templateViews['topnav'], nulltrue);
 
       $templateSidenav     $this->load->view($this->templateViews['sidenav'], nulltrue);
 
       $templateSiteContent $this->load->view($this->templateViews['content'], nulltrue);
 
       $templateFooter      $this->load->view($this->templateViews['footer'], nulltrue);

 
       $this->load->view(
 
           'template',
 
           array(
 
               'templateHead'        => $templateHead,
 
               'templateHeader'      => $templateHeader,
 
               'templateTopnav'      => $templateTopnav,
 
               'templateSidenav'     => $templateSidenav,
 
               'templateSiteContent' => $templateSiteContent,
 
               'templateFooter'      => $templateFooter,
 
           )
 
       );
 
   }

 
   protected function setContentView($view)
 
   {
 
       $this->setTemplateView('content'$view);
 
   }

 
   protected function setPageTitle($title)
 
   {
 
       if (! empty($title)) {
 
           $this->templatePageTitle $title;
 
       }
 
   }

 
   protected function setTemplateView($part$view)
 
   {
 
       $this->templateViews[$part] = $view;
 
   }


Some examples of how to use these methods:
PHP Code:
<?php

class Something extends MY_Controller
{
 
   public function __construct()
 
   {
 
       parent::__construct();

 
       $this->lang->load('something');

 
       // Set a default page title for this controller,
 
       // in case we don't set it in a method below.
 
       $this->setPageTitle($this->lang->line('something_page_title_default'));
 
   }

 
   public function index()
 
   {
 
       $this->setPageTitle($this->lang->line('something_page_title_index'));

 
       // This should load a view from /views/Something/index.php into the
 
       // $templateSiteContent region.
 
       $this->render();
 
   }

 
   public function xampp()
 
   {
 
       // This should load /views/Something/xampp.php
 
       $this->render();
 
   }

 
   public function more()
 
   {
 
       // Load a model and get some data to pass to our view.
 
       $this->load->model('some_model');
 
       $someData $this->some_model->getSomething();

 
       // By passing 'templatePageTitle', we don't have to make a
 
       // separate call to $this->setPageTitle().
 
       // $someData will now be available as $some_data in our views.
 
       $this->render(array(
 
           'some_data'         => $someData,
 
           'templatePageTitle' => $this->lang->line('something_page_title_more')
 
       ));
 
   }

 
   public function less()
 
   {
 
       // Instead of displaying /views/Something/less.php, 
 
       // this will display /views/Something/else.php
 
       $this->setContentView('Something/else');
 
       $this->render();
 
   }

 
   public function strange()
 
   {
 
       // Change the header to /views/Something/header.php
 
       $this->setTemplateView('header''Something/header');

 
       // This will still load /views/Something/strange.php
 
       $this->render();
 
   }

Reply


Messages In This Thread
RE: Detailed Explanation of a Controller & Model? - by mwhitney - 08-31-2015, 09:00 AM



Theme © iAndrew 2016 - Forum software by © MyBB