Welcome Guest, Not a member yet? Register   Sign In
Correct MVC Use
#1

[eluser]visormatt[/eluser]
Hopefully someone will have an answer that will turn that light on in my head because I am about to go crazy... But from what I understand so far I should be generating my dynamic results using models by way of the controller they are accessed but basically I have my views set up nicely...

So here is the problem... If i generate my results in the Controller I am not sure how to pass those results directly to the view? Or is that a no-no...

model ->

Code:
class Test_model extends Model {
    
    function Test_model() {
    
        parent::Model();
        $this->load->helper(array('url'));
        
    }
        
    function test1() {
                
        $data = $this->db->query("
            SELECT * FROM users");
                
        $output = "<div>";
        foreach($data->result() as $rResources) {
            $output .= "<div class='formUser dropShadow rounded10'>
            <h2>" .$rResources->user_id ."</h2>
            <h2>" .$rResources->user_name ."</h2>"
            ."</div>";
        }
        $output .= "</div>";
        
    }    
}

Controller ->

Code:
class Test_controller extends Controller {

    function Test_controller() {
    
        parent::Controller();
                
        $this->load->helper(array('url', 'form', 'date'));    
        $this->load->library(array('encrypt', 'session'));
        
    }

    function index() {
    
        $this->load->model('Test_model');
        
        $data['output'] = $this->Test_model->test1();
        
        $this->load->view('/global/header');
        $this->load->view('/test_view', $data);
    
    }
    
}


View ->
Code:
&lt;?php echo date('m/d/Y'); ?&gt;

--- I want to have the resulst created here ---  &lt;?php $output; ?&gt;
#2

[eluser]Johan André[/eluser]
Model:
Code:
&lt;?php
class Test_model extends Model
{
    
    public function __construct()
    {
        parent::Model();
    }
    
    public function get()
    {
        $this->db->select('*');
        $this->db->from('users');
        return $this->db->get()->result();
    }
    
}

Controller:
Code:
&lt;?php
class Test extends Controller
{
    
    public function __construct()
    {
        parent::Controller();
    }
    
    public function index()
    {
        $this->load->model('test_model');
        
        $data = array();
        $data['items'] = $this->test_model->get();
        
        $this->load->view('test', $data);
    }
    
}

View:
Code:
<div>
    &lt;? foreach($items AS $item) : ?&gt;
    <div class="formUser dropShadow rounded10">
        <h2>&lt;?=$item->user_id?&gt;</h2>
        <h2>&lt;?=$item->user_name?&gt;</h2>
    </div>
    &lt;? endforeach; ?&gt;
</div>
&lt;?=date('m/d/Y'); ?&gt;
#3

[eluser]visormatt[/eluser]
Works perfect, thank you! Would you mind reading over what I assume is happening here? If you see anything wrong please call me a dummy and point it out Smile Thank you again

1. create the results in the model

Code:
return $this->db->get("SELECT * FROM users")->result();

2. assign it as an array in the controller

Code:
$data['items'] = $this->user_model->get_users();

3. parse the array in the view
Code:
&lt;?php foreach($items as $item) : ?&gt;
    <div class="formUser dropShadow rounded10">
        <h2>&lt;?php echo $item->user_id; ?&gt;</h2>
        <h2>&lt;?php echo $item->user_name; ?&gt;</h2>
    </div>
    &lt;?php endforeach; ?&gt;
#4

[eluser]brianw1975[/eluser]
Dummy! No, just kidding hehe

Part 2 is correct, but in a limited fashion, think in more general terms.

return the data from the model, and then in the controller you can also call helpers to manipulate the data (text formatting, date formatting -- some would argue on these, and it is a purely semantic argument, I prefer my view files as clean as possible), possibly send the data to yet another Model, etc then send it off to the view.

but other than that small nit-pick, you got the idea.
#5

[eluser]visormatt[/eluser]
Thank you both for your help Smile I am currently going through FAR TOO much work that I had already developed... Sadly I have to be honest and say that I was pretty much set-up using only Controllers and Views -> so I am moving in the right direction and I am already seeing the difference its making...

With that said I will be back with more questions tomorrow Sad hahaha
#6

[eluser]Johan André[/eluser]
I think you got!
Just one note - use the database activerecord functions as far as possible. they automatically produce "safe" queries. In some cases the AR is not able to help you, then use custom queries.

When I first looked at MVC frameworks I was puzzled because I come from a "traditional" PHP coding world.
But when I understood the concept of splitting code into models, controllers, libraries and views I got alot more productive. At first it can look like having alot of files for simple tasks, but in the long run it's SO much more friendly.

My projects almost always starts like this:

1. Analyze the different parts of the site (for instance blog, portfolio, downloadpage, staffpages etc.)

2. Describe (on paper) what data needs to stored for each part and in what ways I need to access it (ie the model). How the data will validate is important to (even though in CI the validation is done in the controller).

3. Sketch out the views (in pure xhtml/css - with dummy data)

4. Design the controllers (Create/Read/Update/Delete)

5. Create the views based on sketches.


One tip for the road:
Use Jamies Base-controller. It's really cool and supports layouts and partials + it automatically fetches the views based on controller/method naming - meaning if you call blog/edit/234 it automatically load the edit.php-view from the blog-folder. Combine it with Carabiner Asset-loader and you got the start of a pretty solid setup. Saves alot of time.

Good luck!
#7

[eluser]visormatt[/eluser]
Johan,

Thanks again for the words of wisdom, much appreciated... This is by far the largest project in which I am designing everything from scratch... My biggest problem at this point is the Client and Project Managers who are preventing me from creating a Final structure/site-map and they continue to request new features... Going out of my f*$king mind....

But just last night I was able to move restructure my code for my Events, Uses and Validation/login models and controllers and added pagination into a good chunk of it as well and just in the pagination I found how useful it is to break the Model(data) out of the controller Smile

Alright, back to the grind and I am sure I will back to the grind... I must say, I am big on trying to exhaust all my ideas, but the CI forum ultimately my saving grace thus far... Well that and some jQuery )
#8

[eluser]visormatt[/eluser]
Johan,

I do have one question regarding what you mentioned... Regarding "producing safe queries" what exactly should i look out for, essentially I am using what I assume are safe queries as the SQL syntax in my statements.
#9

[eluser]The Wizard[/eluser]
why not sticky that topic or add it under tutorials or such? Smile
#10

[eluser]Johan André[/eluser]
[quote author="visormatt" date="1262744237"]Johan,

I do have one question regarding what you mentioned... Regarding "producing safe queries" what exactly should i look out for, essentially I am using what I assume are safe queries as the SQL syntax in my statements.[/quote]

Often the fetching from database requires some parameters that can be manipulated maliciously by users. They usually come from the url (like posts/delete/{id}) or from a post-request.
These values need to be escaped so the "hacker" can't change the purpose of the query.
AR does this automatically. Doing it manually would mean running everything thru mysql_escape_string()-function.




Theme © iAndrew 2016 - Forum software by © MyBB