Changing my MVC view class to allow AJAX response to use views

Viewed 107

I have an MVC system which serves my web content through a URI. (www.something.com/view/me) and controllers serve a model and then a view.

Sometimes, I have content which requires client side interaction before it can generate content. In this case, a search based on location which needs the client to provide the location. Therefore I am calling the page, then calling a different URI using ajax and retrieving the html content to place on the page.

This works when I place the php/html directly in a model and echo it. I then use javascript in the ajax call to fill the void with the new content. But this is not neat. I would rather have all my presentation (even the dynamically generated stuff) in my views. How can I change the view class in my MVC to allow this?

I should point out that my current view class uses 'require' to output the view. However this i not suitable for ajax returns. Only a direct output will work.

I have tried file_get_contents('/view/generated_view') with a file location but this outputs raw code with no php parser in the flow. (I have also tried to run it as a direct url file_get_contents('www.something.com/view/generated_view') but the rules of MVC don't allow direct access to views.) I have also tried eval() but again, this has not worked and I want to avoid.

I will carry on and use the model to generate the html for output but is there something I am missing? a method I have not thought of?

1 Answers

You could use something like this.

class View {
    protected $template;
    protected $viewName;
    protected $params;

    public function __construct($viewName, $params = array()){
        $this->viewName       = $viewName;
        $this->params         = $params;  
        $this->render();
    }
    
    protected function render(){
        if(empty($this->viewName)){
            throw new Exception("ERROR: the view name is empty.");
        }
        
        $this->template = $this->getContentTemplate();
        echo $this->template;
    }
    
    protected function getContentTemplate()
    {
        $templatePath = TEMPLATE_PATH . "/{$this->viewName}.php";
        if(!is_file($templatePath)){
            throw new Exception("ERROR: The template {$this->viewName} do not exists.");
        }
        
        $view = (object) $this->params; // the object $view can be used directly in the template
        
        ob_start(); // opens output buffer
        
        require($templatePath); // require template file, it's hold on the buffer
        
        $template = ob_get_contents(); // get the buffer content
        
        ob_end_clean();
        
        return $template;
    }
}

It´s a simple view class but you'll get it.

Related