Search code examples
phpmodel-view-controllerrenderer

Render header (with separate MVC files) in home page MVC?


My 'Home' controller gets data and stores it all inside its $data array. This array will be passed to the view (the setOutput() method) and echo'ed there. Now I have a 'Header' controller that does the exact same thing as the 'Home' controller. Getting data, passing it to the header view, etc. How do I load my page header into the 'Home' view?

I tried to load the 'Header' controller into $data['header'], within my 'Home' controller, but it returns the entire header object (header controller class).

Controller looks like this:

class Home extends Controller {
    public function index() {
        // Stores data in data variable
        $data = array(
            'foo' => 'bar',
            'key' => 'value',
            'etc' => 'another'
        );

        $data['header'] = $this->load->controller('path/to/header');
        
        // Send data to view file
        $this->response->setOutput($data, 'home');
    }
}

setOutput($data, 'home') method looks like this:
I thought I might need to render the header object here in some way?

public function setOutput($data = array(), $route) {

    $path = explode('/', trim($route, '/'));
    $file = end($path);
    $incl = '';

    foreach ($path as $dir) {

        if ($dir != $file) {
            $incl .= $dir . '/';
        }
    }

    $incl .= $file . '.php';

    require_once(DIR_VIEW . $incl);
}

Solution

  • Will a lot is unkown what is behind your methods it is hard to answer. But i think the the problem for your question is:

    Your mehtods dont have return type (string) they print the output directly. At least this is what the require_once of a view file looks like.

    If you want to keep this architecture, you may need to use output buffering with ob_start() and ob_get_cean() and so on...

       ob_start();
       $this->load->controller('path/to/header');
       $data['header'] = ob_get_clean();
    

    What @Code4R7 seems also true to me. Seems like an unfamiliar usage of MVC.