简体   繁体   中英

mvc architecture in php best practices

What is best practice for creating php mvc app. I am asp.net developer where controller linked with view .But I saw in php mvc tutorial that view has two data member of controller and model type. View is used to call a propitiate controller with controller type of object and model. view has information about both controller and model where controller only knew about model.

class model{
 //code..
}
class controller{
priavate $model;//model type object
//code..
}
class view{
   private $model;//model type of object
   private $controller//controller type of object
   //code..
 }

But in asp.net mvc controller decide which view to call when certain event occur . Controller information about both model and view. view can have model type of object only.which in php will as follow

class model{
 //code..
}
class controller{
private $model;//model type object
private view;/view type object
//code..
}
class view{
   private $model;//model type of object
          //code..
 }

Which one is best approach in php to create view type of object in controller or controller type of object in view.

Thanks a lot!

Php does not come with an MVC structure "out of the box". There are several ways to implement an MVC structure, you can build your own.

Some useful articles: https://r.je/mvc-in-php.html

http://www.sitepoint.com/the-mvc-pattern-and-php-1/

I personally create a Tempalte class wich methods allows to add data to the selected view.

Here an example:

   <?php

/**
 * Description of Template
 *
 * @author yuri.blanc
 */
class Template {
    private $template = TEMPLATE;
    private $message = array();
    /**
     *
     * @var array
     */
    private $var = array();
    private $view;

    /**
     * 
     * @param array $args
     */
    public function renderArgs($name, $value){
        $this->var[$name] = $value;
    }

    public function render($controller, $view) {
        $ctrl = strtolower($controller);
        $this->page_content = $this->view = APP_ROOT."/view/$ctrl/$view.php";
        $this->renderArgs("template", $this->template);
        $this->renderArgs("page_content", $this->page_content);
        extract($this->var);
        include APP_ROOT."template/$this->template/index.php";
    }

    }

In that way, your target view will have $name variable with $value as data. To create a view, you just do what you need on the controller and then you use render($controller,$view) on the template instance after adding your "args". (files are view/CONTROLLER/VIEW.php).

In this example php template files acts as a static container, where the view files are included (main-container).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM