Welcome Guest, Not a member yet? Register   Sign In
Examples of using the Model class?
#1

[eluser]Doug Lerner[/eluser]
Hi, I am a newbie to CI.

Are there any examples of small apps that make use of the Model class and active records to create a database, create some tables, add/modify/delete records and some basic things like that?

I think if I can see one basic example that puts it all together it would make things a lot clearer.

Thanks!

doug
#2

[eluser]Colin Williams[/eluser]
[quote author="Doug Lerner" date="1215518910"]I think if I can see one basic example that puts it all together it would make things a lot clearer.[/quote]

Here's a good example. This Model method handles the saving of an object (whether it is a new object or a pre-existing one), in this case, a User.

A seemingly simple operation easily comes quite complex. However, by keeping this in a model, you make your edit user and create user controller methods much more simple, leaving room for the complexity of validation, etc.

Code:
function save_user($user)
   {
      $status = FALSE;
      $this->ci->load->library('encrypt');
      
      // Prepare core user data and insert/update new user model
      if (!isset($user->uid))
      {
         $user->uid = FALSE;
      }
      // Encrypt password
      $user->password = $this->ci->encrypt->encode($user->password);
      // Set created time to GMT in absence of an existing time (like new account)
      if (!isset($user->created) or $user->created == '')
      {
         $now = time();
         $user->created = gmdate("U", $now);  
      }
      $user_data = array(
         $user->uid,
         $user->created,
         $user->email,
         $user->password,
         $user->status,
         // Funny way to handle our bindings and ON DUPLICATE KEY UPDATE values, but it's effective
         $user->created,
         $user->email,
         $user->password,
         $user->status,
      );
      if ($user->uid)
      {
         $user_sql = 'INSERT INTO ' . $this->config['user_table'] . ' (uid,created,email,password,status) VALUES (?,?,?,?,?)';
         $user_sql .= 'ON DUPLICATE KEY UPDATE created = ?, email = ?, password = ?, status = ?;';
      } else {
         // Shift off the uid from the user_data since this is a new entry
         array_shift($user_data);
         $user_sql = 'INSERT INTO ' . $this->config['user_table'] . ' (created,email,password,status) VALUES (?,?,?,?)';
      }
      $status = $this->ci->db->query($user_sql, $user_data);
      
      // DELETE users attributes then INSERT the new ones, if they exist
      if (!$user->uid)
      {
         $user->uid = $this->ci->db->insert_id();
      }
      $this->ci->db->delete($this->config['attribute_table'], array('uid' => $user->uid));
      if (is_array($user->attribute))
      {
         $attribute_sql = 'INSERT INTO ' . $this->config['attribute_table'] . ' (`uid`, `key`, `value`) VALUES';
         foreach ($user->attribute as $key => $value)
         {
            if (is_array($value))
            // Handle attributes with multiple values
            {
               foreach ($value as $item)
               {
                  $attribute_sql .= ' (' . $this->ci->db->escape($user->uid) . ', ' . $this->ci->db->escape($key) . ', ' . $this->ci->db->escape($item) . '),';
               }
            }
            else
            // or just update regular ones
            {
               $attribute_sql .= ' (' . $this->ci->db->escape($user->uid) . ', ' . $this->ci->db->escape($key) . ', ' . $this->ci->db->escape($value) . '),';
            }
         }
         // Clean the SQL and run the query
         $attribute_sql = substr($attribute_sql, 0, strlen($attribute_sql) - 1);
         $status = $this->ci->db->query($attribute_sql);
      }
      
      // Cache the user
      $this->users[$user->uid] = $user;
      
      // Return the status of the save, should be TRUE
      return $status;
   }
#3

[eluser]Doug Lerner[/eluser]
Thanks. I will take a look through that code for sure.

And if there are any other complete examples out there - like a tutorial maybe that says (1) create this file in the models folder, (2) this in the controllers and (3) this in the views and here we tie them all together, it would be useful.

I would be happy to contribute such a tutorial myself if I ever figure it all out. Smile

doug
#4

[eluser]Colin Williams[/eluser]
K.. quick tut. Very very simple.

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;
#5

[eluser]Doug Lerner[/eluser]
Thanks. That was useful.

One question - how did the tables in the database get created to begin with? Is there something equivalent to RoR "migration" that takes the model and creates tables with the appropriate fields and all in CI?

Thanks,

doug
#6

[eluser]Colin Williams[/eluser]
Either you executed MySQL commands from the command line to create your database and table, or you used a web-based MySQL client like phpMyAdmin to set up the database and tables, or you used a desktop client like Navicat (Windows).

I typically use phpMyAdmin
#7

[eluser]Doug Lerner[/eluser]
Or I supposed you could also execute MySQL requests from inside some initialization function in the model class to do it, couldn't you? Or in real-time check for the existence of a table before using it and creating it if it doesn't exist?

Or are there active record functions which do that?

Isn't it better to automate things rather than stop and create tables manually?

Thanks,

doug
#8

[eluser]Colin Williams[/eluser]
Quote:Isn’t it better to automate things rather than stop and create tables manually?

Not a bad idea if you're going to distribute the App or reuse it a lot. Otherwise, I plan my database schema first, build it out, then start coding. You could also do it dynamically in something like an install script. But if you're just creating a bespoke App with a narrow scope, I don't think that complexity is necessary
#9

[eluser]Doug Lerner[/eluser]
Correct me if I'm wrong... I'm admittedly a super-newbie at CI....

I am getting the impression that since the Model part of MVC is "optional" in CI that what gets put into the models folder are really more or less "database helper functions" which might just as well be in the controllers folder as functions in a class definition there.

Is there a practical difference - something with the naming conventions of the framework, that make it useful to have these functions inside the models folder hierarchy?

Another thing I'm still not getting from the examples and discussion and docs so far - is there anything in CI per se that helps set up basic CRUD for a database table (in the way scaffolding and database migration does in Ruby on Rails, for example)? It seems that it takes as much time to set up a basic CRUD framework for a database table in CI as it would if doing it outside the framework.

But as I said, I am an admitted newbie at CI. Any other thoughts on how the framework assists in setting things up?

Thanks!

doug
#10

[eluser]Colin Williams[/eluser]
CodeIgniter's own stated philosophy, and mine as well:

Quote: * The Model represents your data structures. Typically your model classes will contain functions that help you retrieve, insert, and update information in your database.
* The View is the information that is being presented to a user. A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of "page".
* The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page.

And no, beyond scaffolding, there is no automated CRUD-type set up in CI core, but there have been several Libraries contributed to expedite CRUD processes. Although, in my experience, a given application component's CRUD process is too unique to farm out to a CRUD-type framework.




Theme © iAndrew 2016 - Forum software by © MyBB