Welcome Guest, Not a member yet? Register   Sign In
OO Inspired view object
#1

[eluser]Hannes Nevalainen[/eluser]
Put this as a library in your library folder.
Library
Code:
class View{
    private $view;
    private $data;
    
    public function __construct($view, $data = array()){
        $this->view = $view;
        $this->data = is_array($data) ? $data : array();
    }
    public function render($echo = false){
        $CI =& get_instance();
        return $CI->load->view($this->view, $this->data, $echo);
    }
    public function __toString(){
        return $this->render(true);
    }
    public function __set($field, $data){
        $this->data[$field] = $data;
    }
    public function __get($field){
        return isset($this->data[$field]) ? $this->data[$field] : null;
    }
}
The implementation is simple but it make it easy and clear to build up your views. Since this lib is using the CI behind the scenes caching would still work!
Example Controller
Code:
class Test extends Controller{
  public function Test(){
    parent::Controller();
  }
  public function index(){
    $main = new View('main');
    $main->content = $view = new View('another_view');
    $view->title = 'Hejsan min vän';
    $main->render();
  }
}

Main view
Code:
<html>
    <head>
        <title>Simple template</title>
    </head>
    <body>
        <?=$content?>
        <!-- Because the veiw object implements __toString() method this would work!-->
    </body>
</html>
Content view
<h1>&lt;?=$title?&gt;</h1>
<p>
Om utvecklaren har gjort som han ska borde detta fungera..
</p>




Theme © iAndrew 2016 - Forum software by © MyBB