我是MVC和OOP的新手,我正在尝试通过教程和自己尝试一些东西来学习它。我有这个代码:
Model.class.php:
class Model {
public $string;
// Add a value to the instance variable $string when object of this class is instantiated
public function __construct(){
$this->string = "MVC + PHP = Awesome!";
}
}
Controller.class.php:
class Controller {
private $model;
// For now, the Controller doesn't do anything, because no controlling features have been implemented yet
public function __construct($model) {
$this->model = $model;
}
}
我的View.class.php:
class View {
private $model;
private $controller;
private $account;
public function __construct($controller,$model) {
$this->controller = $controller;
$this->model = $model;
$this->account = $account;
}
// Return the value of the $string variable
public function output(){
return $this->model->string;
}
}
这是我的index.php,其中一个简单的字符串被回显,作为上述代码的结果:
$model = new Model();
$controller = new Controller($model);
$view = new View($controller, $model);
$account = new Account();
// Execute the output() function from the View class to output the text
echo $view->output();
我自己创建了帐户类,它应该输出'Yoo'而不是'PHP + MVC = Awesome!'看起来像这样:
class Account extends Model {
// Add a value to the instance variable $string when object of this class is instantiated
public function __construct(){
$this->string = "Yoo";
}
}
当我return $this->model->string;
时,它会正确输出PHP + MVC = Awesome!
。但是当我做return $this->account->string
时,它什么也没输出。没有错误或任何东西。为什么这不起作用?
答案 0 :(得分:1)
这个答案只是MVC的基本示例
非常重要
实际上,您的索引文件应该只运行Application类或将请求路由到良好控制器和方法的东西。但是,如果你想要开始,你不需要做一些非常复杂的事情。
(在我看来)
这里你的主要错误是认为它是你的索引文件调用模型,然后将它传递给你将传递给视图的控制器。在MVC中,控制器应该能够自己完成所有这些操作,一旦被调用。
仍在大行
索引文件实例化控制器,然后调用此控制器的方法。控制器调用模型,收集数据并将其发送回控制器,控制器将此数据发送到良好视图(仍由控制器调用),然后视图将显示结果。
<强>的index.php 强>
<?php
// i have only one controller, with only one action, so i call it.
// i havnt autoloader so i do all requires here
require_once 'MyController.php';
require_once 'MyModel.php';
require_once 'MyView.php';
$Controller = new MyController();
$Controller->exampleAction();
<强> MyController.php 强>
<?php
class MyController
{
public function exampleAction()
{
$model = new MyModel();
$view = new MyView();
$view->send($model->data());
}
}
<强> MyModel.php 强>
<?php
class MyModel
{
public function data()
{
return 'Some data from the model';
}
}
<强> MyView.php 强>
<?php
class MyView
{
public function send($data)
{
echo $data;
}
}
顺便说一句,控制器可以有一个专用模型,然后你可以在他的构造函数中加载它
<强> MyController.php 强>
<?php
class MyController
{
protected $Model;
public function __construct()
{
$this->Model = new MyModel();
}
public function exampleAction()
{
$view = new MyView();
$view->send($this->Model->data());
}
}
视图相同。
希望这个答案能帮助你理解MVC的工作原理^^