许多框架决定使用这种方法:强制用户扩展基本控制器类(如果要创建新控制器)或扩展基础模型类(如果要创建新模型).
我们来看看CodeIgniter控制器基类的代码:
/**
* Constructor
*/
public function __construct()
{
self::$instance =& $this;
// Assign all the class objects that were instantiated by the
// bootstrap file (CodeIgniter.php) to local class variables
// so that CI can run as one big super object.
foreach (is_loaded() as $var => $class)
{
$this->$var =& load_class($class);
}
$this->load =& load_class('Loader', 'core');
$this->load->initialize();
log_message('debug', "Controller Class Initialized");
}
Run Code Online (Sandbox Code Playgroud)
它有什么作用?好吧,就我所知,它只是允许我们使用$this->load->...例如.
让我们来看看__get()模型基类的神奇方法:
/**
* __get
*
* Allows models to access CI's loaded classes using the same
* syntax as controllers.
*
* @param string
* @access private
*/
function __get($key)
{
$CI =& get_instance();
return $CI->$key;
}
Run Code Online (Sandbox Code Playgroud)
它完全一样.这种做事方式带来了什么?
PRO
$this->....缺点
parent::__construct()类构造中的get_instace() 被预定了$this->instance 重新定义会导致致命错误现在让我们来看看另一种方法:
创建一个静态类,例如App执行基本控制器执行的所有操作:例如, $this->load->...将是App::load->....
现在再次考虑利弊:
PRO
App::....parent::__construct()类构造中的缺点
$this->性感语法???题
这里提出了一个真正的问题:与CI相比,第二种方法是更好还是更差?为什么?
专业版
- 您可以通过 App::.... 访问有用的 CI 类
- 您不必强迫用户扩展基类
- 您不必强制用户在类构造中调用parent::__construct() 方法
- 名称或属性名称被保留
这并不完全有效。CI 从不强迫开发人员扩展基类。所有核心框架功能都可以轻松扩展。您可以在文件夹MY_Controller.php内application/core包含您自己的基类,例如:
Front_Controller extends CI_Controller{
// Share common properties or functionalities across front/public controllers here
}
Admin_Controller extends CI_Controller{
// Share common properties or functionalities across administrative controllers here
}
Run Code Online (Sandbox Code Playgroud)
然后,parent::parent_method()在PHP中很常见。如果您确实在应用程序中使用面向对象设计,大多数情况下您会在其他地方使用此语法。这使您能够向子类添加功能,而不会丢失从父类继承的功能。
所以回答你的问题:
真正的问题来了:与 CI 方法相比,第二种方法是更好还是更差?为什么?
这两种尝试都可以被认为是合法的,atm。因为,事实上:1)CI 引导程序中没有一致性检查(类似于instanceof CI_ControllerPHP 5 或is_aPHP4),2)并且,CI 不会强制您从控制器操作方法返回任何内容(一个Response对象,例如例如,SF)。
也就是说,您可以让任意一个类充当控制器。事实上,您不需要将核心控制器功能包装在静态类中,没有人阻止您在这些任意类中使用get_instance()->load->library('foo')and 。get_instance()->load->database()
| 归档时间: |
|
| 查看次数: |
2101 次 |
| 最近记录: |