用户
 找回密码
 入住 CI 中国社区
搜索
查看: 4541|回复: 6
收起左侧

《CodeIgniter 走马观花》对codeigniter的分析

[复制链接]
发表于 2008-4-21 11:54:43 | 显示全部楼层 |阅读模式
廖宇雷在《CodeIgniter 走马观花》中有一段对codeigniter的分析,谁来发表自己的见解,深入分析一下其中的设计原理和缘由。原文链接:
http://www.dualface.com/blog/?p=358

codeigniter/Base
codeigniter/Base4.php 和 codeigniter/Base5.php 功能一样,只不过分别适用于 PHP4 和 PHP5 而已。其中定义了 CI_Base 类和一个非常重要的 get_instance() 函数。
get_instance() 函数返回一个 CI_Base 类在整个应用程序中的唯一实例。
这里有一个有趣的发现。Base4.php 和 Base5.php 中的 CI_Base 和 get_instance() 有这完全不同的实现。
在 Base4.php(对应 PHP4)中,CI_Base 直接继承自 CI_Loader。CI_Base 实例化时,将自身的引用保存到了 CI_Base::$load 中。也就是说 CI_Base 实例的 $load 实际上指向自己。然后 $load被复制到一个名为 $OBJ 的全局变量。
在 PHP4 版的 get_instance() 函数中,如果检查到 $CI(这是 CI_Base的实例,也就是控制器的实例)存在,就返回 $CI,否则返回全局变量 $OBJ->load。但由于在 PHP4中,$OBJ->load 实际上就是一个 CI_Base 的实例。所以。。。。所以。。。。。。还是返回了一个 CI_Base的实例。真搞不懂作者为什么这样写,简直要让人发疯。
不管怎么样,应用程序其他地方调用 get_instance() 都会获得一个 CI_Base 的实例。
在 Base5.php(对应 PHP5)中,用一个 singleton 模式来解决了这个问题。因此 CI_Base 也不再需要从CI_Loader 继承了。不过这也留下了隐患(CI_Loader 实例要什么时候获取呢?),所以在 CI_Base 的继承类Controller 中,只好通过判断是否是运行 PHP5 来决定是不是要实例化一个 CI_Loader。
真的很无语啊,这种设计虽然可以用,但是很糟糕。在 PHP4 种,CI_Loader 的方法和成员变量暴露在了 CI_Base 中。如果应用程序不小心调用了这些方法或使用了这些成员变量。那么应用程序在 PHP5 中运行就会出错。
发表于 2008-4-21 12:15:26 | 显示全部楼层
首先,我个人认为他文中对 CI 的分析有个人感情因素在里面,有些用词有失偏颇。
其次,我他文中的一些分析不适合新版的 CI。
发表于 2008-4-21 12:35:45 | 显示全部楼层
没研究源码,我没发言权
发表于 2008-4-21 16:52:54 | 显示全部楼层
在 PHP4 种,CI_Loader 的方法和成员变量暴露在了 CI_Base 中。如果应用程序不小心调用了这些方法或使用了这些成员变量。那么应用程序在 PHP5 中运行就会出错。


这个我个人觉得和CI无关。

Base4.php的确是有点让人晕。。。我也搞不懂为啥要设计成那样的- -
发表于 2008-4-22 10:47:59 | 显示全部楼层
这篇文章的作者不是fleaphp的作者吗?他从codeigniter中借鉴了大量的思想到fleaphp中
发表于 2008-4-22 13:13:12 | 显示全部楼层
原帖由 沧蓝 于 2008-4-21 16:52 发表


这个我个人觉得和CI无关。

Base4.php的确是有点让人晕。。。我也搞不懂为啥要设计成那样的- -


* CI_BASE - For PHP 4
*
* This file is used only when CodeIgniter is being run under PHP 4.
*
* In order to allow CI to work under PHP 4 we had to make the Loader class
* the parent of the Controller Base class.  It's the only way we can
* enable functions like $this->load->library('email') to instantiate
* classes that can then be used within controllers as $this->email->send()
*
* PHP 4 also has trouble referencing the CI super object within application
* constructors since objects do not exist until the class is fully
* instantiated.  Basically PHP 4 sucks...
*
* Since PHP 5 doesn't suffer from this problem so we load one of
* two files based on the version of PHP being run.

注释中已经写了为什么要这样用了
发表于 2008-4-22 13:37:33 | 显示全部楼层
原帖由 qq123 于 2008-4-22 10:47 发表
这篇文章的作者不是fleaphp的作者吗?他从codeigniter中借鉴了大量的思想到fleaphp中

没错,就是 FleaPHP 的作者。

本版积分规则