2014-02-11 4 views
1

Я пытаюсь понять шаблон MVC, и у меня есть некоторые проблемы с ним. вот пример, который работает и является полуавтоматическим шаблоном MVC.Принципы MVC понимают, почему

class model { 
    public $string; 

    public function __construct(){ 
     $this->string = 'awsome MVC'; 
    } 
} 


class view { 
    private $model; 
    private $controller; 

    public function __construct($controller, $model){ 
     $this->controller = $controller; 
     $this->model = $model; 
    } 

    public function output(){ 
     return '<b>'.$this->model->string.'</b>'; 
    } 
} 


class controller {  
    private $model; 

    public function __construct($model){ 
     $this->model = $model; 
    } 
} 

$model = new Model(); 
$controller = new controller($model); 
$view = new view($controller, $model); 
echo $view->output(); 

У меня проблемы с этим, почему это вид обработки больше, чем контроллер? ниже у меня есть мой (я думаю) сценарий MVC, и я надеюсь, что вы, ребята, можете указать, что я делаю неправильно, и почему приведенный выше пример лучше.

<?php 

/* 
* this is the view 
*/ 
class template 
{  
    function html($input){ 
     return 'template : <b>'.$input.'</b>'; 
    } 
} 

/* 
* this is the model 
*/ 
class database 
{ 
    function output(){ 
     return 'this is a news title'; 
    } 
} 

/* 
* this is the basic controller 
*/ 
class basicController 
{ 
    public $model; 
    public $view; 

    public function loadModel($model){ 
     $this->model = new $model; 
    } 

    public function loadView($view){ 
     $this->view = new $view; 
    } 
} 

/* 
* this is the extended controller 
*/ 
class newsController extends basicController 
{  
    public function __construct(){   
     $this->loadModel('database'); 
     $this->loadView('template'); 
    } 

    public function showAction(){ 
     return $this->view->html($this->model->output()); 
    } 
} 

/* 
* calling 
*/ 
$controller = new newsController; 
echo $controller->showAction(); 

?> 
+2

Где именно вы обнаружили, что * «официальный официальный образец MVC» *, потому что это дерьмо. Просмотр не должен иметь доступ к контроллеру. –

+1

http://r.je/mvc-in-php.html – SinisterGlitch

+0

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

ответ

0

Прежде всего, ваше определение «полуофициальный шаблон MVC» неверно.

Вот простейший «правильный» MVC-шаблон, который я мог бы придумать.

Я знаю, что понимание принципов MVC иногда может быть затруднительным, но вместо написания собственной мини-рамки я бы рекомендовал заглянуть в Laravel. Это хорошо документированная и многофункциональная современная структура, которая может показаться трудной для изучения, но поверьте мне, после того, как вы правильно освоите основы, вы не ошибетесь.

<? 

/* 

Model represents a single entity. It doesn't have to be read or saved to the database. 
Example models: User, Post, Comment, Auction. 
Model class is used to operate on the model data, such as calculating the age of the user or calculating a comment count for a post. 
*/ 
class Model { 

    static function get($id) { 
     return $obj; // Returns an object with given ID from the DB 
    } 

    static function all() { 
     return $objc; // Returns all the objects. 
    } 

} 

class User extends Model { 
    public $name; 
    public $surname; 
} 

/* 

Controller handles the logic of the "app". It's used to load both the data and views and combine them together to serve output to the client. 
Please keep in mind, that sometimes a controller can be used without the need of a model object (static pages) or view object (json output) 

*/ 
class Controller { 

    public function index() { 
     $models = User::all();  
     $view = new View('index_view'); 
     $view->set('models', $models); 

     return $view->render(); 
    } 

    public function show($id) { 
     $model = User::get($id); 

     $view = new View('single_view'); 
     $view->set('model', $model); 

     return $view->render(); 
    } 

} 

/* 

View class is used to handle template loading and parsing. You can just include raw PHP files or create complex parsing rules 

*/ 
class View { 

    protected $file_name; 
    protected $fields; 

    public function __construct($filename) { 
     $this->file_name = $filename; 
    } 

    public function set($key, $value) { 
     $this->fields[$key] = $value; // Store variable in the fields array 
    } 

    public function render() { 
     extract($this->fields); // Make all the variables visible for the template file 
     include($this->file_name); // Include the template file 

     // You can add a buffer here to return the parsed template as a string. (see ob_flush() and ob_start()) 
    } 

} 

// single_view.php 
<h1> Hello <?= $model->name ?></h1> 

// index_view.php 
<table> 
    <? foreach($models as $model) { ?> 
     <tr> 
      <td><?= $model->name ?></td> 
      <td><?= $model->surname ?></td> 
    <? } ?> 
</table> 
+0

Спасибо, приятель, за этот пример, если бы я мог поддержать вас, я бы сделал это (но я не могу). Я видел 10+ разных версий MVC, и это самый лучший из всех. Я реализую ваш стиль и играю с ним, пока он не станет интуитивно понятным. – SinisterGlitch

+0

Не могли бы вы объяснить, что случилось с шаблоном MVC от Laravel? –

+0

Хорошим началом было бы «это не MVC». –

Смежные вопросы