HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Where should I put menu items in MVC with PHP - Model or Controller?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mvcwithphpwhereputcontrollermenuitemsshouldmodel

Problem

This is my first attempt with MVC and I almost get it, but a small thing bothers me.

I have this controller in CodeIgniter:

_menu(), $page);
            $data['menuItems'] = $this->_menu();

            $this->load->view('templates/header', $data);
            $this->load->view('templates/menu', $data);
            $this->load->view('pages/'.$page, $data);
            $this->load->view('templates/footer', $data);
    }

    private function _menu()
    {
        static $menuItems = array(
                           "Home page" => "home",
                           "Our history" => "history",
                           "About us" => "about",
                           "Contact page" => "contact"
                       );

        return $menuItems;
    }
}


And here is the menu view:

 $view) {
    $menu .= '';
        $menu .= '';
    } else {
        $menu .= '>';
    }
    $menu .= $menuName . '' .PHP_EOL ;
}

echo $menu;


Where do the menu items belong in MVC logic? Is it ok to store things like the menu in the Controller or do I have to make a new Model for it like this?

class Menu extends CI_Model {

    public function __construct()
    {
        parent::__construct();
    }

    public function get_menu_items()
    {
        static $menuItems = array(
                           "Home page" => "home",
                           "Our history" => "history",
                           "About us" => "about",
                           "Contact page" => "contact"
                       );

        return $menuItems;  
    }
}


Then load it from Controller:

public function index($page = "home")
{
    ...
    $this->load->model('Menu');
    $data['menuItems'] = $this->Menu->get_menu_items();

    $this->load->view(...);
    $this->load->view(...);
    $this->load->view(...);
}

Solution

This a nice example: it shows how the MVC is just a pattern which should be ajusted to your needs.

  • The menu items you're showing seem very unlikely to change over time. This means you can simply put them in your "templates/menu" view.



  • If they're shared among multiple views, then the controller is OK.



  • If the menu items can change dynamically, then your model can provide a meaningful abstraction over your data, and then it would go into a model.

Context

StackExchange Code Review Q#11277, answer score: 4

Revisions (0)

No revisions yet.