Search code examples
phpapachelamp

PHP Vars From Included Bootstrap Not Showing Up in View


I have created my own little PHP framework for fun, however, I am having trouble passing variables from bootstrap to the views....

if I put an echo,print_r,var_dump my target variable in the bootstrap, the output is displayed in the browser before the tag... yet the target var in bootstrap.php is not available in the view, it is coming up as "" even though at the top of the page it is being output correctly....

Somethings I noticed from similar questions:

- The target variable is not being over written
- The include target path is correct and the file exists
- The file is only being included one time (include_once is only fired once)

Any ideas are greatly appreciated, I am pulling my hair out over here lol...

Source Code 

https://gist.github.com/jeffreyroberts/f330ad4a164adda221aa


Solution

  • If you just want to display your site name, I think you can use a constant like that :

    define('SITE_NAME', "Jeff's Site");
    

    And then display it in your index.tpl :

    <?php echo SITE_NAME; ?>
    

    Or, you can send your variables to the view by extending a little bit your JLR_Core_Views :

    class JLR_Core_Views
    {
        private $data;
    
        public function loadView($templatePath, $data = array())
        {
            $this->data = $data;
            $templatePath = JLR_ROOT . '/webroot/' . $templateName . '.tpl';
            if(file_exists($templatePath)) {
                // Yes, I know about the vuln here, this is just an example;
                ob_start();
                include_once $templatePath;
                return ob_get_clean();
            }
        }
    
        function __get($name)
        {
            return (isset($this->data[$name]))
                ? $this->data[$name]
                : null;
        }
    }
    

    Then, you can call your template like that :

    $view = new JLR_Core_Views();
    $view->loadView("index", array("sitename" => "Jeff's Site"));
    

    And here is your index.tpl :

    <?php echo $this->siteName; ?>
    

    Below is another example of what you can do.

    First, you create this class in order to store all the variables you want :

    <?php
    class JLR_Repository {
    
        private static $data = array();
    
        public function set($name, $value) {
            self::$data[$name] = $value;
        }
    
        public function get($name) {
            return (isset(self::$data[$name]))
                ? self::$data[$name]
                : null;
        }
    }
    ?>
    

    Then, when you want to store something in it :

    JLR_Repository::set("sitename", "Jeff's Site");
    

    And in your index.tpl :

    <?php echo JLR_Repository::get("sitename"); ?>