【发布时间】:2011-07-10 15:24:34
【问题描述】:
我不确定这个问题的标题是否准确,所以请多多包涵。
我正在创建一个轻量级的 MVC 框架。它的工作原理有点像这样:
Main.php(主类)调用
- 控制器扩展了 Main ($this->controller) 和
- 模型扩展了 Main ($this->model)
现在模型和控制器类将根据 URI 调用控制器和模型(例如,Blog.php [扩展控制器])。
(回顾一下:Main.php 调用 $this->model 和 $this->controller。Controller 类调用 Blog extends Controller)。
如何从 Blog.php 中访问 Controller 中的函数,以及 Main 中的函数?
我问这个是因为在 Controller 中我需要访问我的 URI 类中的函数,但我不能这样做,因为当我执行 $this->uri 时 PHP 告诉我该对象不存在。
在 every 类中执行 $this->controller、$this->model 和 $this->uri 似乎是不好的做法。
我的一个朋友建议我使用一种叫做 __get() 的魔法方法。这看起来对吗?
class Main
{
function __construct() {
loadClasses();
loadUri();
}
function loadClasses() {
$this->controller = new Controller();
$this->uri = new Uri();
$this->load = new Load();
}
function loadUri() {
//Using the uri, determine what Controller to load.
}
}
class Controller
{
...
}
class Blog extends Controller
{
$this->load->view(); //Should access the view function in the load class
}
【问题讨论】:
-
要么您误用了“扩展”一词,要么您严重误用了 OOP。
-
从 Blog.php 中,如何访问 Controller 中的函数,以及 Main 中的函数? - 使用 parent 引用父类中的方法
parent::method_from_Controller();
标签: php oop model-view-controller frameworks