Welcome Guest, Not a member yet? Register   Sign In
I'm Exhausted - Give me a hand here!
#6

[eluser]Colin Williams[/eluser]
Here's a very basic example of MVC interaction that I posted for doug ealier:

Here's the run down. The Blog Controller is called because the user enters our blog URL. We load the blog model to handle retrieving our data. We use the model to retrieve the data and pass it into the view. Our view loops through the result from the model and displays it in a manner we want.

Excuse the brevity and shit HTML Tongue Also, if this is all our Blog controller did, ever, a model might be slight overkill (a framework might even be overkill for this!). But it is highly likely your App and its interaction with your database will be much more complex.

Controller in controllers/blog.php

Code:
class Blog extends Controller {
  
   function Blog()
   {
      parent::Controller();

      // Load the model and assign to $this->blog
      $this->load->model('Blog_model', 'blog');
   }

   function index()
   {
      // Get 5 blog posts from our model
      $data['posts'] = $this->blog->get_latest(5);
      // Pass result to view for display
      $this->load->view('blog/front', $data);
   }
}

Model in models/blog_model.php

Code:
class Blog_model extends Model {
  
   function Blog_model()
   {
      parent::Model();
   }

   function get_latest($limit = 1)
   {
      $result = array(); // We should always return an array so our views don't choke in a foreach loop
      // Prepare the query
      $this->db->limit($limit);
      $this->db->orderby('created', 'desc'); // Get most recent first
      // Run the query and update $result if a result is found
      $query = $this->db->get('blog');
      if ($query->num_rows() > 0)
      {
         $result = $query->result();
      }
      return $result;
   }
}

View in views/blog/front.php

Code:
<html>
  <head>
    <title>My Blog Posts</title>
  </head>
  <body>
    <? if (count($posts)) : ?>
    <? foreach ($posts as $post) : ?>
      <h2>&lt;?= $post->title ?&gt;</h2>
      &lt;?= $post->body ?&gt;
    &lt;? endforeach; ?&gt;
    &lt;? else: ?&gt;
    <p>No blog posts yet!</p>
    &lt;? endif; ?&gt;
  &lt;/body&gt;
&lt;/html&gt;


Messages In This Thread
I'm Exhausted - Give me a hand here! - by El Forum - 07-09-2008, 03:43 PM
I'm Exhausted - Give me a hand here! - by El Forum - 07-09-2008, 03:47 PM
I'm Exhausted - Give me a hand here! - by El Forum - 07-09-2008, 03:57 PM
I'm Exhausted - Give me a hand here! - by El Forum - 07-09-2008, 04:02 PM
I'm Exhausted - Give me a hand here! - by El Forum - 07-09-2008, 05:11 PM
I'm Exhausted - Give me a hand here! - by El Forum - 07-09-2008, 07:02 PM
I'm Exhausted - Give me a hand here! - by El Forum - 07-09-2008, 11:09 PM



Theme © iAndrew 2016 - Forum software by © MyBB