Jump to content

Help with default variables in my simple View class in my Model-View-Controller


cgm225

Recommended Posts

Currently I have a simple Model-View-Controller, in which I have a simple View class.  The View class has a render method that receives an array from a helper class, and this array ($this->viewData) is turned into variables which are then used in a template.

 

So the flow is like this:

 

An array is passed to the View class -> the array keys and values are turned into variables -> those variables are used in a template.

 

An example would be:

 

[website_title] => Example.com  ----->  $website_title = Example.com; -----> echo $website_title (within the title tags in the template)

However, I also want to have default variables provided in the class somehow such that, if a required variable is not provided in the passed array, then the default value would be loaded.

 

So, with the example above, if the passed array does not contain the website_title, then the default website_title will be loaded from somewhere.

 

Currently, my View class does the behavior I have just described (see below).  However, I feel like there is probably a better way to do this instead of including "hard coded" variables in the class.

 

Any ideas?

 

class View extends ActionController {

    public function render() {

        //Default variables, (To be placed in an outside/included file(?))
        $title = "Example.com";

        //This foreach function goes over all of the elements in $this->viewData array, creates
        //a variable for every value, and the name of the value (the variable name) is the key's value.
        foreach ($this->viewData as $key => $value) {
            $$key = $value;
        }

        //Including a template file within which variables are echoed
        require_once $this->pageDir . "/default.tpl";
    }
}

 

Thank you all in advance!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.