Search code examples
phpcodeignitermodel-view-controller

MVC quandaries, should this go in view or controller?


I was wondering what the best practice would be for where to place a certain piece of code, either controller or view (or even model if I'm way off).

Currently, the application retrieves information from the database, one column is "type". Then based on the type, there is a switch statement that prepares the html tags to be displayed in the view.

Something like:

    foreach ($data as &$dataPoint)
    {
        foreach ($dataPoint as &$postItem)
        {
            switch ($postItem['type'])
            {
                case "image":
                    $postItem['content'] = "<img src=\.$postItem['content']."\" />";
                    break;
                case "youtube":
                    $postItem['content'] = "<iframe src=\"http://www.youtube.com/embed/".$postItem['content']."?showinfo=0\" frameborder=\"0\"></iframe>";
                    break;
            }
        }
    }

But I'm just lost as to where this should go, should it be directly in the controller, before it's passed on to the view? Or should it be placed on the top of a view file?


Solution

  • Yep in your view, like others have mentioned.

    You can indeed create a view format helper file to take care of some non-generic php functions

    foreach ($data as &$dataPoint)
        {
            foreach ($dataPoint as &$postItem)
            {
                //format_helper.php
                get_content_type($postItem);
            }
        }
    

    format_helper.php

    if(!function_exists('get_content_type'){
        function get_content_type(array $postItem){
             switch ($postItem['type'])
                {
                    case "image":
                        echo "<img src=\.$postItem['content']."\" />";
                        break;
                    case "youtube":
                        echo "<iframe src=\"http://www.youtube.com/embed/".$postItem['content']."?showinfo=0\" frameborder=\"0\"></iframe>";
                        break;
                }
        }
    })