CodeIgniter Forums
MVC Hierarchy question. - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forum-21.html)
+--- Thread: MVC Hierarchy question. (/thread-4938.html)



MVC Hierarchy question. - El Forum - 12-25-2007

[eluser]smalter[/eluser]
Hi all!

Firstly, i would like to congratulate the community for this great work!

I decided, after long hesitancy, to begin using a PHP Framework. Smile

This is my first experience with the MVC architecture, i have searched in the official documentation and this forum for a long time, but i dont understand something.

I have a main view, and it contain an other view (footer of my page), this footer must contain some data coming of a controller.

These data are generated with a controller and a model for database query.

When i want to include this footer in other pages, data (of my database) is not displayed, my variable containing these data do not exist.

Probably i forget something in the documentation, my english are not being very good. :roll:

I hope for someone will understand my message, in spite of my English writing.

Thanks a lot!

PS: Si quelqu'un parle le français dans le coin, je serais très content qu'il puisse m'aiguiller dans mes débuts difficiles. Smile


MVC Hierarchy question. - El Forum - 12-25-2007

[eluser]spheroid[/eluser]
Do you have an example of your controller, model, and view? This might help to solve your problem.

(French): Est-ce que vous avez des exemples de votre controller, modèle, et vue? Ça puisse aider a répondre de votre problème.


MVC Hierarchy question. - El Forum - 12-26-2007

[eluser]xwero[/eluser]
Why do you need a controller for data? You could create a model method that outputs your data the way you want to see it in your footer.

Or are you talking about a form in your footer that needs to be submitted. Then you could make a controller method that is only used to process the submit and redirect to the page the user was on when the form was submitted.
Code:
//view
<div id="footer">
&lt;form action="/someclass/somemethod" method="post"&gt;
&lt;input hidden="redirect" value="/otherclass/othermethod"&gt; &lt;!-- changes per page --&gt;
...
&lt;/form&gt;
</div>
// controller
someclass extends controller
{
   ...
  
   function somemethod()
   {
      // validation, regenerate footer data
      redirect($this->input->post('redirect'));
   }
}



MVC Hierarchy question. - El Forum - 12-26-2007

[eluser]Sarfaraz Momin[/eluser]
Well I don't know weather I understood your problem completely but I think this is what you want. You want to display a footer in all your pages and show some data from the controller in that footer but since you are calling the footer in the page view you are not able to get the data array passed to the footer view. If I am correct here what you can do:

refer user guide: Loader Class

Code:
$this->load->view('file_name', $data, true/false)

The third optional parameter lets you change the behavior of the function so that it returns data as a string rather than sending it to your browser. This can be useful if you want to process the data in some way. If you set the parameter to true (boolean) it will return data. The default behavior is false, which sends it to your browser. Remember to assign it to a variable if you want the data returned:

that means, you have to set the last parameter to TRUE! then you can echo multiple views.
Code:
echo $this->load->view(’myfile’, $data, true);
echo $this->load->view(’myfile2’, $footerdata, true);

Hope this makes sense.

Good Day !!!


MVC Hierarchy question. - El Forum - 12-26-2007

[eluser]smalter[/eluser]
EDIT: Ok. I think that you are better going to understand with the exemple.
By thinking, i want to include a *controller* in my other views... But I know that it is not a solution.


Thanks for your help!

Exemple:
Code:
// Shop: Main Controller
class Shop extends Controller {
  function shop {
    parent::Controller();
    // Load somes library, plugins or helper
    $this->load->helper('blabla');
    $this->load->library('blabla');
    $this->load->model('my_model');
  }

  function index() {
    $data['title'] = 'This is my shop!';
    $data['list_item'] = $this->my_model->lastentries();
    $this->load->view('homepage', $data);
}
}

// Homepage: Main view
// Load header view
&lt;?=$this->load->view('header', $data)?&gt;
&lt;?=$this->load->view('content_of_my_page', $data)?&gt;

// Display last entries in the bottom of the page
&lt;?=$this->load->view('lastentries_view', $data)?&gt;
&lt;?=$this->load->view('footer', $data)?&gt;

// Lastentries_view: view
&lt;?
&lt;?php foreach($list_item as $item): ?&gt;
echo $item->lastentries();
&lt;?php endforeach;?&gt;
?&gt;

Ok, it is working.

But now, i decide to include "lastentries_view" in an other view "contact.php", on the top.

I make a new view and controller:
Code:
// Contact controller
class Contact extends Controller {
  function contact {
    parent::Controller();
    // Load somes library, plugins or helper
    $this->load->helper('blabla');
    $this->load->library('blabla');
  }

  function index() {
    $data['title'] = 'Contact page';
    $data['content'] 'Content of my contact page';
    $this->load->view('contact', $data);
}
}

// Contact: view

// Load header view
&lt;?=$this->load->view('header', $data)?&gt;

// Display last entries before the content
&lt;?=$this->load->view('lastentries_view', $data)?&gt;

&lt;?=$content;?&gt;
&lt;?=$this->load->view('footer', $data)?&gt;

In the second exemple, the value "$list_item" used in "lastentries_view" doesn't exist.
This is make an error.

How I can get organized to be able to move a view (lastentries_view) and display it in different other views, but by keeping the access to variables? (Homepage on the bottom, Contact page on the top,...)

Cheers. Smile


MVC Hierarchy question. - El Forum - 12-26-2007

[eluser]xwero[/eluser]
I think the best way is to extend your base controller or use a template library so you don't have the repeat the header and footer in every controller method you create.

edit : if you do a forum search for these two solutions you will find a lot of information


MVC Hierarchy question. - El Forum - 12-26-2007

[eluser]smalter[/eluser]
EDIT: if an admin read this topic, he could modify the subject to "MVC Architecture (French users welcome!)"?. Thx

Thank's for your help!

But I still searched on the forum but i could not resolve my problem. Sad

I try to load multiple controllers (even if it is not recommended), create my own library, but in my case, it returns to the same that to use a model. I am still forced to "load" functions of my library, if i want to add/delete a "modules" in one of my views, i owe to delete him from my controller and from my view.

I think what i want to make is very simple:

In Classic PHP:
--------------------------
For exemple:

module.php:

// Connection to database
// Output HTML

homepage.php:

// Include module.php
// Include module2.php
// Include module3.php

If i dont want to display module2.php in my homepage, i delete the line include('module2.php') from my homepage. Smile
--------------------------

I definitely understood that this question is often asked on this forum, but i'm lost. Sad

Very sorry for my english, but i love CI and i want to use all her capacities. Wink

Thank's!

PS: Si quelqu'un parle francais par ici, un peu aide en français serait la bienvenue. Merci d'avance!


MVC Hierarchy question. - El Forum - 12-26-2007

[eluser]John_Betong[/eluser]
Hi Smalter,

The way I understand MVC is that the Controller's job is to gather data and to distribute the data to the views.

Can you try this approach to your existing code then edit __header.php, __content.php and __footer.php separately.

// Shop: Main Controller
Code:
class Shop extends Controller {
  function shop {
    parent::Controller();
    // Load somes library, plugins or helper
    $this->load->helper('blabla');
    $this->load->library('blabla');
    $this->load->model('my_model');
  }

  function index() {

    $data['htmltitle']    = 'This is my shop!';
    $data['list_item']    = $this->my_model->lastentries();

    $data['header']       = $this->load->view('__header',             $data, TRUE) ;
    $data['content']      = $this->load->view('__content_of_my_page', $data, TRUE);
    $data['footer']       = $this->load->view('__footer',             $data, TRUE);

    $output = $this->load->view('homepage',                           $data, TRUE);
    echo $output;
  }

}
&nbsp;

// Homepage.php: Main view
Code:
&lt;?= $header ?&gt;
  &lt;body style='background:#000 none; color:#fff'&gt;

     <div style='background:#ff0 none; color:#f00; width:80%; margin:2em auto'>

       &lt;?=$content ?&gt;

       &lt;?=$footer ?&gt;

    </div>

&lt;/body&gt;
&lt;/html&gt;
&nbsp;

__header.php
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

&lt;html lang="en-GB"&gt;
&lt;head&gt;
  &lt;title&gt;&lt;?= isset($debug) ? $debug : $htmltitle ?&gt;&lt;/title&gt;
&lt;/head&gt;
&nbsp;

__content.php
Code:
<h1>Content goes here</h1>
<pre>
&lt;?= print_r($data) ?&gt;
</pre>
&nbsp;

__footer.php
Code:
<h1>Footer goes here</h1>
<pre>
&lt;?= print_r($data) ?&gt;
</pre>


Cheers,

John_Betong
&nbsp;


MVC Hierarchy question. - El Forum - 12-30-2007

[eluser]smalter[/eluser]
Hi all,

I think that i understand somes important thing which missed in my CI logic.

- URI Class
- Redirect function

In my logic, one page = one controller...
I definitely understood that it was not good method.

Then, now i have one "main" function, and, based on URI, which load all the view.

Code:
function load() {
    $uri = $this->uri->segment(3,'home');
    $data = array(
    'last_registred' => $this->members->last_registred(),
    'connected' => $this->members->connected(),
    'registred' => $this->members->registred());
    
    $this->load->view('a2n/'.$uri,$data);
    }

Good?

Now, i can load views dynamically with my $data availaible on her.

But everything is not ok.

In my view "events", i can use $data['last_registred'], $data['connected'], etc,... Nice. But i also want to make a query to get all events from my "events" table.

What's the best way for that?

Create new functions? And in theses functions, re-create my $data array?

Thank's for your help!

Santiago

----------------------------------- En français / In french

Bonjour à tous,

j'ai compris certaines choses importantes qui m'avaient completement échapées.

- La classe URI
- La fonction "redirect" que je peux utiliser dans mes controleurs.

En fait, dans ma logique, pour chaque page, je devais créer un controleur, ce qui n'est pas très simple à gérer... Wink Mais j'ai maintenant bien compris que ce n'était pas la bonne méthode.

Donc, maintenant j'ai un controleur principal, avec une fonction qui va charger la bonne vue en fonction du paramètre que je passe dans l'URI.

Code:
function load() {
    $uri = $this->uri->segment(3,'home');
    $data = array(
    'last_registred' => $this->members->last_registred(),
    'connected' => $this->members->connected(),
    'registred' => $this->members->registred());
    
    $this->load->view('a2n/'.$uri,$data);
    }

Jusque là c'est correct?

Je peux donc accèder à mes variables $data['connected'], $data['registred'], etc,... Dans toutes mes vues qui sont loadé par cette fonction. Parfait.

Mais pour ma vue "agenda" par exemple, je dois aussi faire une requète SQL pour récupérer les éléments de ma table "agenda".

Qu'elle est la meilleures manière de procéder?

Je suis obligé de faire une fonction différente?

J'aimerais pouvoir faire des requètes supplémentaire, pour appeller ma table agenda par exemple, mais sans devoir recréer dans chaque fonction mon array $data principal qui contient $connected, $last_registred, etc,...

Merci d'avance!

Santiago