Switching from controller to view

I am working on creating my own very simple MVC, and I'm brainstorming to move from a controller to a view. Which involves sending variables from a class to just an old PHP page.

I am sure that this has been considered before, but I wanted to see what ideas people can come up with.

//this file would be /controller/my_controller.php

class My_Controller{

   function someFunction(){

  $var = 'Hello World';
  //how do we get var to our view file in the document root?
  //cool_view.php

   }

}
+5
source share
5 answers

Some kind of hash table is a good way to do this. Return your variables as an array of associations that fills all the gaps in your view.

+1
source

Save the variables as a property in the controller object, then retrieve them when rendering

class My_Controller {

    protected $locals = array();

    function index() {
        $this->locals['var'] = 'Hello World';
    }

    protected function render() {
        ob_start();
        extract($this->locals);
        include 'YOUR_VIEW_FILE.php';
        return ob_get_clean();
    }
}

__get __set,

$this->var = 'test';
+1

MVC most simple way, ...

class My_Controller
{

   function someFunction() {
       $view_vars['name'] = 'John';
       $view = new View('template_filename.php', $view_vars);
   }

}

class View
{
   public function __construct($template, $vars) {
       include($template);
   }
}

template_filename.php

Hello, <?php echo $vars['name'];?>

PHP Savant http://phpsavant.com/docs/

+1

Zend_View .

View AbstractView on github - unfortunaly ( svn), .

View ( ), ( php-) . $this.

- :

<?php
class View
{
  public function render()
  {
    ob_start();
    include($this->_viewTemplate); //the included file can now access $this
    return ob_get_clean();
  }
}
?>

, :

<?php
class Controller
{
  public function someAction()
  {
    $this->view->something = 'somevalue'; 
  }
}
?>

:

<p><?php echo $this->something;?></p>

, .

+1

MVC PHP, , PHP.

, - Command + Factory.

.

interface ControllerCommand
{
    public function execute($action);
}

:

class UserController implements ControllerCommand
{
    public function execute($action)
    {
        if ($action == 'login')
        {
            $data['view_file'] = 'views/home.tpl.php';
        }
        else if ($action == 'edit_profile')
        {
            $data['view_file'] = 'views/profile.tpl.php';
            $data['registration_status'] = $this->editProfile();
        }

        return $data;
    }
}

:

$data = ControllerCommandFactory::execute($action);
if (!is_null($data)) { extract($data); }
/* We know the view_file is safe, since we explicitly set it above. */
require $view_file;

, Controllercommand execute .

MVC , theodore [at] phpexperts.pro.

0

All Articles