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

(This post was last modified: 08-31-2015, 06:30 AM by Josh1985. Edit Reason: code block formatting errors )

Hi all,

Can anyone explain for a newbie to CodeIgniter a pratical example of how to set up a tabular template using <div> tags in CodeIgniter? What I mean is this: I have spent hours scouring the web looking for a PRACTICAL version of step by step tutorials that not only explains the general idea of what a controller is and does but I would like some instruction on how you are supposed to know when and how to call in say a CI library, arbitrary HTML code, or php code. I have a pretty firm understanding of HTML in that every tag has an open tag a and a close tag, where they go in a html document and why. BUT, when it comes to codeigniter every tutorial I have found only either covers the same thing the codeigniter manual does-which is just a brief overview of how everything works together. OR it shows you how someone created a controller for what they are trying to do which in no way relates to what I am trying to do. What I am hoping someone can help me do is this:

I already have 4 HTML pages created outside of codeigniter for a custom XAMPP dashboard for myself, all up and working. What I am looking to do is take my existing pages and have codeigniter load in the static content such as the header, main container's html, the topnav html, the left nav html, sitecontent area html, and the footer into one single views file then have the dynamic content that changes page to page be inserted into its respective page's sitecontent area. This way I can avoid having to make changes to all 4 html files to change a "template element" such as adding a nav link; if I were to do that.

Below is the code for the index page to give you an example. I will include the others in the next post should you all need them.

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>
 <meta content="en-us" http-equiv="Content-Language">
 <meta content="text/html; charset=windows-1252" http-equiv="Content-Type">
 <title>XAMPP Dashboard</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" />
</head>
<body>
<div id="main">
 <div id="logo"><img alt="XAMPP" src="/images/logo/xampp.png"></div>
 <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>
 <div id="columns">
  <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>
  <div id="contents" class="column">
    <div id="sitecontent">
    <h1>Welcome to <font face="Arial Rounded MT Bold"><font size="inherit">XAMPP</font></font> for Windows 5.6.11</h1>
     You have successfully installed XAMPP on this system! Now you can start using Apache, MySQL, PHP and other components. You can find more info in the<a href="/">FAQs</a> section or check the <a href="/">HOW-TO Guides</a> for getting started with PHP applications. Start the XAMPP Control Panel to check the server status.
    <h1>Community</h1>
     XAMPP has been around for more than 10 years – there is a huge community behind it. You 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+</a> circles.
    <h1>Contribute to <font face="Arial Rounded MT Bold"><font size="inherit">XAMPP</font></font>translation</h1>
     Can you help translate XAMPP for other community members? We need your help to translate XAMPP into different languages. We have set up a site, <a href="https://translate.apachefriends.org/">translate.apachefriends.org</a>, where users can contribute translations.
    <h1>Install applications on <font face="Arial Rounded MT Bold"><font size="inherit">XAMPP</font></font> using Bitnami</h1>
    Apache Friends and Bitnami are cooperating to make dozens of open source applications available on XAMPP, for free. Bitnami-packaged applications include Wordpress, Drupal, Joomla! and dozens of others and can be deployed with one-click installers. Visit 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.
    </div>
   </div>
  </div>
<div id="footer">Page created by: Josh Davis.<br>&copy<a href="http://www.apachefriends.org">Apache Friends</a></div>
</div>
</body>
</html>

Any help you could offer would be greatly appreciated!
Thank you again,
Josh
Reply
#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
#3

(08-31-2015, 09:00 AM)mwhitney Wrote: 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();
 
   }


Thank you for your helpful and lengthy post. I am however, still somewhat confused. Please pardon me while I get some clarification on some things.

First the view files are located in:

-------------------------------------------------------
/application/views/
-------------------------------------------------------

And are the following:
-------------------------------------------------------
head.php
header.php
topnav.php
sidenav.php
footer.php
xampp.php
template.php
-------------------------------------------------------

The controller file should be located in:

-------------------------------------------------------
/application/controllers/
-------------------------------------------------------
 
and is this file:
-------------------------------------------------------
MY_Controller.php
-------------------------------------------------------

Am I right so far?

Assuming I am correct, I have heard that usually the template, head, header, and footer view files go in:

-------------------------------------------------------
/application/views/includes
-------------------------------------------------------
is that true?

Secondly, with all those files in place, when i try open that project directory at the root i get the default codeigniter page? Am I supposed to specify the dir of the codeigniter site and the controller class and the private function in order to see the page put together? as you see below:

-------------------------------------------------------
/project1/MY_Controller/private
-------------------------------------------------------

Or is there something else I am missing?

Thanks again,
Josh
Reply
#4

(09-01-2015, 03:38 AM)Josh1985 Wrote: Thank you for your helpful and lengthy post. I am however, still somewhat confused. Please pardon me while I get some clarification on some things.

First the view files are located in:

-------------------------------------------------------
/application/views/
-------------------------------------------------------

And are the following:
-------------------------------------------------------
head.php
header.php
topnav.php
sidenav.php
footer.php
xampp.php
template.php
-------------------------------------------------------

Yes, althought xampp.php should be in a sub-directory named after your controller (so, in my example, /application/views/Something/xampp.php).

Quote:The controller file should be located in:

-------------------------------------------------------
/application/controllers/
-------------------------------------------------------
 
and is this file:
-------------------------------------------------------
MY_Controller.php
-------------------------------------------------------

This should be /application/core/MY_Controller.php, because we're extending the CI_Controller (/system/core/Controller.php).

Quote:Assuming I am correct, I have heard that usually the template, head, header, and footer view files go in:

-------------------------------------------------------
/application/views/includes
-------------------------------------------------------
is that true?

You could do that, if you wish. You would just have to change the values in $templateViews (in MY_Controller) to reflect the sub-directory (for example: 'header' => 'includes/header'). I tend to think of "includes" as a location for legacy scripts, so I would go with something like "themes" or "templates", maybe with an additional sub-directory so I can setup multiple templates in the same directory (i.e. 'themes/default/header').

Quote:Secondly, with all those files in place, when i try open that project directory at the root i get the default codeigniter page? Am I supposed to specify the dir of the codeigniter site and the controller class and the private function in order to see the page put together? as you see below:

-------------------------------------------------------
/project1/MY_Controller/private
-------------------------------------------------------

Or is there something else I am missing?

Thanks again,
Josh

You only use the methods in MY_Controller through another controller, so I included the Something controller (which would go in /application/controllers/Something.php) which extends MY_Controller. That means that any public or protected method (function) or property (variable) in MY_Controller is available in the Something controller. The properties in MY_Controller which are marked "private" are only accessible by MY_Controller and its methods. That's why we have to have methods in MY_Controller which set those properties if we want the Something controller to be able to change them.

If you don't set a route, assuming the CodeIgniter site is available from http://localhost, when you go to http://localhost/something, CodeIgniter is going to look for a controller named Something.php in /application/controllers. Since there is only one URI segment, it looks for a method in that controller named index(). So, http://localhost/something and http://localhost/something/index take you to the same page, which is loaded by the controller at /application/controllers/Something.php via the index() method, which, given the example code will attempt to load the view from /application/views/Something/index.php.

If you visit http://localhost/something/xampp, it will load the same controller (/application/controllers/Something.php), but look for the xampp() method. This method will load the view in /application/views/Something/xampp.php.

If you wanted to change what URL takes you to a given controller/method, you would have to modify the routes in /application/config/routes.php.
Reply
#5

(09-01-2015, 09:29 AM)mwhitney Wrote:
(09-01-2015, 03:38 AM)Josh1985 Wrote: Thank you for your helpful and lengthy post. I am however, still somewhat confused. Please pardon me while I get some clarification on some things.

First the view files are located in:

-------------------------------------------------------
/application/views/
-------------------------------------------------------

And are the following:
-------------------------------------------------------
head.php
header.php
topnav.php
sidenav.php
footer.php
xampp.php
template.php
-------------------------------------------------------

Yes, althought xampp.php should be in a sub-directory named after your controller (so, in my example, /application/views/Something/xampp.php).



Quote:The controller file should be located in:

-------------------------------------------------------
/application/controllers/
-------------------------------------------------------
 
and is this file:
-------------------------------------------------------
MY_Controller.php
-------------------------------------------------------

This should be /application/core/MY_Controller.php, because we're extending the CI_Controller (/system/core/Controller.php).



Quote:Assuming I am correct, I have heard that usually the template, head, header, and footer view files go in:

-------------------------------------------------------
/application/views/includes
-------------------------------------------------------
is that true?

You could do that, if you wish. You would just have to change the values in $templateViews (in MY_Controller) to reflect the sub-directory (for example: 'header' => 'includes/header'). I tend to think of "includes" as a location for legacy scripts, so I would go with something like "themes" or "templates", maybe with an additional sub-directory so I can setup multiple templates in the same directory (i.e. 'themes/default/header').



Quote:Secondly, with all those files in place, when i try open that project directory at the root i get the default codeigniter page? Am I supposed to specify the dir of the codeigniter site and the controller class and the private function in order to see the page put together? as you see below:

-------------------------------------------------------
/project1/MY_Controller/private
-------------------------------------------------------

Or is there something else I am missing?

Thanks again,
Josh

You only use the methods in MY_Controller through another controller, so I included the Something controller (which would go in /application/controllers/Something.php) which extends MY_Controller. That means that any public or protected method (function) or property (variable) in MY_Controller is available in the Something controller. The properties in MY_Controller which are marked "private" are only accessible by MY_Controller and its methods. That's why we have to have methods in MY_Controller which set those properties if we want the Something controller to be able to change them.

If you don't set a route, assuming the CodeIgniter site is available from http://localhost, when you go to http://localhost/something, CodeIgniter is going to look for a controller named Something.php in /application/controllers. Since there is only one URI segment, it looks for a method in that controller named index(). So, http://localhost/something and http://localhost/something/index take you to the same page, which is loaded by the controller at /application/controllers/Something.php via the index() method, which, given the example code will attempt to load the view from /application/views/Something/index.php.

If you visit http://localhost/something/xampp, it will load the same controller (/application/controllers/Something.php), but look for the xampp() method. This method will load the view in /application/views/Something/xampp.php.

If you wanted to change what URL takes you to a given controller/method, you would have to modify the routes in /application/config/routes.php

Thank you for your help thus far. I recently been studying up on multiple views and finally got the 4  HTML pages into 8 codeigniter views + the controller. However, I think I have decided to take a different tact with this design. Here is my idea: I want to have 1view hold all my static content ie. (header, logo, top_nav, left_nav, sitecontent area, and footer), we'll call that the "template" and then load each page's DYNAMIC content from a separate view that only loads the content that changes page to page. Here's why: I originally started out with 4 HTML pages which in the early stages seemed like not a bad idea. Then I got to looking at multiple views, which got me thinking there has to be an easier way then having to change 2 navigations on 4 pages-a ridiculous 4 times. So that got me thinking about multiple views. But as I experimented with it the more I found out I can't just create an HTML template view and then load in the view for the dynamic content inside of that page. So that brings me here... Below is the current code I have for the multiple views setup.

Controller
Site.php

PHP Code:
<?php

class Site extends CI_Controller {
 
 public function 
index()  {
 
$this->home();
 }
 
       public function home()  {
 
$this->load->view('header');
 
               $this->load->view('logo');
 
$this->load->view('top_nav');
 
$this->load->view('left_nav');
 
$this->load->view('content_home');
 
$this->load->view('footer');
 }


Views
header.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>
 <meta content="en-us" http-equiv="Content-Language">
 <meta content="text/html; charset=windows-1252" http-equiv="Content-Type">
 <title>XAMPP Dashboard</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" />
</head>

logo.php

Code:
<body>
<div id="main">
  <div id="logo"><img alt="XAMPP" src="/images/logo/xampp.png"></div>

top_nav.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>

left_nav.php

Code:
  <div id="columns">
   <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>

content_home.php

Code:
   <div id="contents" class="column">
    <div id="sitecontent">
     <h1>Welcome to <span class="xampp">XAMPP</span> for Windows 5.6.11</h1>
      You have successfully installed XAMPP on this system! Now you can start using Apache, MySQL, PHP and other components. You can find more info in the<a href="/">FAQs</a> section or check the <a href="/">HOW-TO Guides</a> for getting started with PHP applications. Start the XAMPP Control Panel to check the server status.
     <h1>Community</h1>
      XAMPP has been around for more than 10 years – there is a huge community behind it. You 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+</a> circles.

 <h1>Contribute to <span class="xampp">XAMPP</span> translation</h1>
      Can you help translate XAMPP for other community members? We need your help to translate XAMPP into different languages. We have set up a site, <a href="https://translate.apachefriends.org/">translate.apachefriends.org</a>, where users can contribute translations.

 <h1>Install applications on <span class="xampp">XAMPP</span> using Bitnami</h1>
       Apache Friends and Bitnami are cooperating to make dozens of open source applications available on XAMPP, for free. Bitnami-packaged applications include Wordpress, Drupal, Joomla! and dozens of others and can be deployed with one-click installers. Visit 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.
</div>
   </div>
  </div>

footer.php

Code:
  <div id="footer">Page created by: Josh Davis.<br>&copy<a href="http://www.apachefriends.org">Apache Friends</a></div>
 </div>
</body>
</html>

CSS
main.css

Code:
@font-face  {
 font-family: "Renaissance-Regular";
 font-style: normal;
 font-weight: normal;
 src: url('/type/renaissance.ttf') format("truetype");
}

body {
 background-image: url('/images/bg/bg1.jpg');
 background-attachment:fixed;
 font-family: "Arial",Arial,Helvetica,sans-serif;
 font-size: 16px;
 color:#009cfc;
}

div {
 border:0px solid #0006ff;
}

table#faq  td.qacolumnhead {
 width:55px;
 font-family:Renaissance-Regular;
 font-size:19px;
 font-weight: bold;
 text-align: center;
}

table#faq  td.qacolumnright  {
 padding-left: 5px;
}

#main {
 background:black;
 position:relative;
 width:80%;
 min-width:500px;
 max-width:920px;
 margin:0 auto;
 border:2px solid #0006ff;
 opacity:0.7;
}

#logo {
 font-family: "Renaissance-Regular";
 font-size: 3.5em;
 text-align: center;
 border-top:0.5px solid #0006ff;
 border-right:1px solid #0006ff;  
 border-bottom:1px solid #0006ff;
 border-left:1px solid #0006ff;
 padding-top:0.5em;
}

.menu ul {
 margin:0;
 padding:0;
 list-style:none outside none;
}

.menu li {
 margin:2px;
}

.horizontal li {
 float:left;
 text-align:center;
}

.menu a:link, .menu a:visited, .menu a:active {
 display:block;
 padding:2px;
 text-align:center;
 text-decoration:none;
 background-color:navy;
 color:#009cfc;
}

.menu a:hover {
 background-color:#333333;
 color:orange;
}

#columns {
 overflow:hidden;
 border-top:2px solid #0006ff;
 margin-top:0px;
}

.column {
 padding-bottom:5000px;
 margin-bottom:-5000px;
}

#toc {
 float:left;
 border-top: 2px solid #0006ff;
}

#toc li {
 width:150px;
 margin:2px;
 border:1px solid #0006ff;
}

#lnav1head, #lnav2head, #lnav2subhead1  {
 background-image: url('/images/bg/40.gif');
 text-align:left;
 font-size: 14px;
 font-weight:bold;
 border-top:0px solid #0006ff;
 border-right:0px solid #0006ff;
 border-bottom:1px solid #0006ff;
 border-left: 0px solid #0006ff;
}

#lnav1menu, #lnav2menu, #lnav2submenu1 {
 background-color:000080;
 text-align:center;
 border-top:1px solid #0006ff;
 border-right:0px solid #0006ff;
 border-bottom:2px solid #0006ff;
 border-left: 0px solid #0006ff;
}

#nav {
 background-color:000080;
 overflow:hidden;
 border-top:1px solid #0006ff;
 border-left:0px solid #0006ff;
}

#nav li {
 white-space:nowrap;
 width:150px;
 margin:2px;
 border:1px solid #0006ff;  
}

#contents {
 border-left:2px solid #0006ff;
 margin-left:156px;
}

#howtoguidenav {
 background-color:000080;
 overflow:hidden;
 border-bottom:2px solid #0006ff;
 border-left:0px solid #0006ff;
}

#howtoguidenav li {
 white-space:nowrap;
 width:300px;
 margin-right:30px;
 margin-left:40px;
 border:1px solid #0006ff;
 border-top:1px solid #0006ff;
 border-radius:6px
}

#sitecontent {
 padding:2px;
}

.xampp {
font-family: "Arial Rounded MT Bold";
font-size:"inherit";
}

#footer {
  clear:both;
 border-top:2px solid #0006ff;
 text-align:center;
}

li {margin: .5em 0; }
h1, h2, h3 {font-family: "Renaissance-Regular"; margin:0; }
h1 {font-size: 2.8em; text-align: center; }
h2 {font-size: 1.5em; text-align: center; }
h3 {font-size: 1em; }  

a:link, a:visited, a:active {
color:#3fb7fe;
text-decoration:none;
}

a:hover {
color: #72cafe;
}

td {
border:1px solid;
}

I would like if someone could tell me how best to take this data and create the single page template and then load in the content like content_home.php. Any help would be greatly appreciated.
Reply
#6

The easiest way to setup a single-page template and load a view into that template is to echo a variable in the template and set that variable to the result of loading the view (making sure to pass true as the third parameter of $this->load->view() so it will return the data instead of staging it for output).

For example, using a template view:
PHP Code:
<!DOCTYPE html>
<
html>
<
head>
    <
title>Example</title>
</
head>
<
body>
    <
div class='content'>
        <?
php echo $contentView?>
    </div>
</body>
</html> 

Then the controller would do something like this:
PHP Code:
$data['contentView'] = $this->load->view('contentView'$contentDatatrue);
$this->load->view('template'$data); 
Reply
#7

(09-08-2015, 06:37 AM)mwhitney Wrote: The easiest way to setup a single-page template and load a view into that template is to echo a variable in the template and set that variable to the result of loading the view (making sure to pass true as the third parameter of $this->load->view() so it will return the data instead of staging it for output).

For example, using a template view:

PHP Code:
<!DOCTYPE html>
<
html>
<
head>
 
   <title>Example</title>
</
head>
<
body>
 
   <div class='content'>
 
       <?php echo $contentView?>
    </div>
</body>
</html> 

Then the controller would do something like this:

PHP Code:
$data['contentView'] = $this->load->view('contentView'$contentDatatrue);
$this->load->view('template'$data); 

Thank you again for all your help! I am a little confused as to one part of the sample code.

In the previous post you will see all the pieces of code that make up my home page. My question is this, if I have 4 pieces of different content views to insert into the template on different pages (home page->content_home, applications page->content_applications, faq page->content_faq, howto page->content_howto).... How does 'content_View' know which piece of content I am calling for on a certain page? As well as the content inside the <title></title> would change. Any thoughts there?

Thanks again

Josh
Reply
#8

(09-09-2015, 10:59 AM)Josh1985 Wrote: In the previous post you will see all the pieces of code that make up my home page. My question is this, if I have 4 pieces of different content views to insert into the template on different pages (home page->content_home, applications page->content_applications, faq page->content_faq, howto page->content_howto).... How does 'content_View' know which piece of content I am calling for on a certain page?

You would change which view you load into $data['contentView'] in the controller. How you do this depends on how you determine which view needs to be loaded. For example, if you have a different method in the controller for each view, you would probably just hard-code it or set it based on the name of the method. On the other hand, if you have a single method which loads multiple possible views, you would probably use a method argument or some other input to determine which view is used.

(09-09-2015, 10:59 AM)Josh1985 Wrote: As well as the content inside the <title></title> would change. Any thoughts there?

You would just set another variable inside the title element:
PHP Code:
<head>
<
title><?php echo $pageTitle?></title>
</head> 

Then, in the controller, you set that variable in the $data passed to your template view:
PHP Code:
// Change this to the name of whatever view needs to be loaded
$contentView 'contentView';

// Set any variables needed by the contentView
$contentData = array();

// Set any variables needed by the template, including the page title for the current page
$data = array('pageTitle' => 'XAMPP Dashboard');

// Load the contentView to be placed into the template view
$data['contentView'] = $this->load->view($contentView$contentDatatrue);

// Load the template.
$this->load->view('template'$data); 
Reply
#9

Thank you for your help so far, could you please paste the code blocks for the index page to study off of in their entirety for the controller and the views cause i tried your suggestions and i keep getting errors.. so i have no idea what i am missing. Thank you
Reply
#10

Why don't you paste the code you're using and the errors you're getting, then I can help you fix them. I'm clearly missing something in my explanations, but it's hard to tell what it is without seeing what you've actually done and what errors you're running into.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB