Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8352657
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T09:01:22+00:00 2026-06-09T09:01:22+00:00

Following this tutorial http://johnsquibb.com/tutorials/mvc-framework-in-1-hour-part-one Im trying to write my first MVC Blog. I understood

  • 0

Following this tutorial http://johnsquibb.com/tutorials/mvc-framework-in-1-hour-part-one Im trying to write my first MVC Blog.

I understood how it works, router.php Calls the suitable page controller. This controller calls the model, Then calls the View page with the returned value.

My question is, What if I want to add to the same news.php page a header\footer. Normally I would write “include(“header.php”). But now when using MVC, how could I implement that?

These are my files:

router.php:

    <?php
/**
 * This controller routes all incoming requests to the appropriate controller
 */
//Automatically includes files containing classes that are called

//fetch the passed request
$pageURL = $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
$path_parts = pathinfo($pageURL);
$page_name = $path_parts['filename']; 
$parsed = explode('?' , $page_name);
//the page is the first element
$page = array_shift($parsed);

// If there is any variables, GET them.
if(!empty($parsed))
{
    $parsed = explode('&' , $parsed[0]);
    $getVars = array();
    foreach ($parsed as $argument)
    {
        //explode GET vars along '=' symbol to separate variable, values
        list($variable , $value) = explode('=' , $argument);
        $getVars[$variable] = urldecode($value);
    }
}

//compute the path to the suitable file
$target ='controllers/' . $page . '_controller.php';

//get target controller
if (file_exists($target))
{
    include_once($target);

    //modify page to fit naming convention
    $class = ucfirst($page) . '_Controller';

    //instantiate the appropriate class
    if (class_exists($class))
    {
        $controller = new $class;
    }
    else
    {
        //did we name our class correctly?
        die('class does not exist!');
    }
}
else
{
    //can't find the file in 'controllers'! 
    die('page does not exist!');
}

//once we have the controller instantiated, execute the default function
//pass any GET varaibles to the main method
$controller->main($getVars);


//  AutoLoad
function __autoload($className)
{        
    // Parse out filename where class should be located
    // This supports names like 'Example_Model' as well as 'Example_Two_Model'
    list($suffix, $filename) = preg_split('/_/', strrev($className), 2);
    $filename = strrev($filename);
    $suffix = strrev($suffix);

    //select the folder where class should be located based on suffix
    switch (strtolower($suffix))
    {    
        case 'model':

            $folder = '/models/';
            $filename = ($className);

        break;

        case 'library':

            $folder = '/libraries/';

        break;

        case 'driver':

            $folder = '/libraries/drivers/';

        break;
    }

    //compose file name
    $file = SERVER_ROOT . $folder . strtolower($filename) . '.php';

    //fetch file
    if (file_exists($file))
    {
        //get file
        include_once($file);        
    }
    else
    {
        //file does not exist!
        die("File '$filename' containing class '$className' not found in
'$folder'.");    
    }
}

?>

post_controller.php

<?php
    /**
     * This file handles the retrieval and serving of posts posts
     */
    class Posts_Controller
    {
        /**
         * This template variable will hold the 'view' portion of our MVC for this 
         * controller
         */
        public $template = 'posts';

        /**
         * This is the default function that will be called by router.php
         * 
         * @param array $getVars the GET variables posted to index.php
         */
        public function main(array $getVars)
        {
            //$b_controller =new  Bottom_Bar_Controller;
            //$b_controller->main($getVars);

            $postsModel = new Posts_Model;

            //get an post
            $post = $postsModel->get_post($getVars['id']);
            //create a new view and pass it our template
            $header = new View_Model('header_template');
            $bottom_bar = new View_Model('bottom_bar');
            $view = new View_Model($this->template);


            //assign post data to view
            $view->assign('header', $header->render(FALSE));
            $view->assign('bottom', $bottom_bar->render(FALSE));
            $view->assign('title' , $post['title']);
            $view->assign('content' , $post['content']);
            $view->assign('date' , $post['date']);
            $view->assign('by' , $post['added_by']);
            $view->render();

        }
    }

posts_model.php

<?php
/**
 * The Posts Model does the back-end heavy lifting for the Posts Controller
 */
class Posts_Model
{
    /**
     * Holds instance of database connection
     */
    private $db;

    public function __construct()
    {
        $this->db = new MysqlImproved_Driver;
    }

    /**
     * Fetches article based on supplied name
     * 
     * @param string $author
     * 
     * @return array $article
     */
    public function get_post($id)
    {        
        //connect to database
        $this->db->connect();

        //sanitize data
        $author = $this->db->escape($id);

        //prepare query
        $this->db->prepare
        (
            "
            SELECT *  FROM `posts`
            WHERE
                `id` = '$id'
            LIMIT 1
            ;
            "
        );

        //execute query
        $this->db->query();

        $article = $this->db->fetch('array');

        return $article;
    }

}
?>

view_model.php

<?php
/**
 * Handles the view functionality of our MVC framework
 */
class View_Model
{
    /**
     * Holds variables assigned to template
     */
    private $data = array();

    /**
     * Holds render status of view.
     */
    private $render = FALSE;

    /**
     * Accept a template to load
     */


    public function __construct($template)
    {

        //compose file name
        $file = SERVER_ROOT . '/views/' . strtolower($template) . '.php';


        if (file_exists($file))
        {

            /**
             * trigger render to include file when this model is destroyed
             * if we render it now, we wouldn't be able to assign variables
             * to the view!
             */
            $this->render = $file;


        }        
    }

    /**
     * Receives assignments from controller and stores in local data array
     * 
     * @param $variable
     * @param $value
     */
    public function assign($variable , $value)
    {
        $this->data[$variable] = $value;
    }

    /**
     * Render the output directly to the page, or optionally, return the
     * generated output to caller.
     * 
     * @param $direct_output Set to any non-TRUE value to have the 
     * output returned rather than displayed directly.
     */
    public function render($direct_output = TRUE)
    {

        // Turn output buffering on, capturing all output
        if ($direct_output !== TRUE)
        {
            ob_start();
        }

        // Parse data variables into local variables
        $data = $this->data;

        // Get template
        include($this->render);

        // Get the contents of the buffer and return it
        if ($direct_output !== TRUE)
        {
            return ob_get_clean();
        }
    }

    public function __destruct()
    {
    }
}

posts.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="../style/style.css" rel="stylesheet" type="text/css" media="screen" />  
<title> Posts (View)</title>
</head>

<body>
       <div id="main">
        <div class="container">
        <?=$data['header'];?>
            <div id="content">  
                <div class="content-background">
                <h2> <?=$data['title'];?></h2>
                <h4> <?=$data['date'];?> </h4>
                <p><?=$data['content'];?></p>
                </div>

            </div>
         </div>
        </div>


    </body>
</html>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T09:01:24+00:00Added an answer on June 9, 2026 at 9:01 am

    Part of the problem is, that your tutorial has a pretty primitive interpretation of MVC-inspired design pattern (you actually cannot implement classical MVC in PHP, but there are patterns, that are based on it).

    View is not just a template. Views are supposed to be class instances, which contain all presentation logic and deal with multiple templates. What you actually have there is a layout template which contains posts template.

    // class \Application\View\Posts
    public function render()
    {
        $layout = new Template( $this->defaultTemplateDirectory . 'layout.html');
        $content = new Template( $this->defaultTemplateDirectory . 'posts.html' );
    
        $layout->assign( 'content' , $content->render() );
    
        return $layout->render();
    }
    

    Also, one of the things, that a view instance should do, is requesting information from the model layer.

    Few materials that you might find useful:

    • Model-View-Confusion part 1: Why the model is accessed by the view in MVC
    • Simple PHP Template Engine
    • How should a model be structured in MVC?

    And if you want to expand you knowledge in OOP, this post contains a list of recommended lectures and books.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to teach myself .Net MVC 3, and am following this tutorial: http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/intro-to-aspnet-mvc-3
I am following this tutorial http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-9 (not exactly same as this) I am trying
Following this tutorial (http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application), I learned how to save data and do concurrency checks
I am following this tutorial http://www.michael-noll.com/tutorials/running-hadoop-on-ubuntu-linux-single-node-cluster/ note: yes I know I did install hadoop
I am following this tutorial: http://www.csharp-station.com/Tutorials/Lesson01.aspx I pasted this into a text file, named
i'm following this tutorial: http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/comment-page-1/#comments to learn how to upload multiple files via ajax.
I'm following this tutorial http://blogs.msdn.com/b/astoriateam/archive/2010/07/21/odata-and-authentication-part-6-custom-basic-authentication.aspx . I need to add to the web.config :
I'm following this tutorial http://msdn.microsoft.com/en-us/library/bb458038.aspx to create a VsPackage Setup. In the part of
I'm trying to add iAd into my project. I'm following this tutorial http://bees4honey.com/blog/tutorial/how-to-add-iad-banner-in-iphoneipad-app/ I
Im pretty new to Linux in general. Ive just been following this tutorial(http://net.tutsplus.com/tutorials/php/how-to-setup-a-dedicated-web-server-for-free/) to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.