|
author:胡旭个人博客
blog:http://www.ihuxu.com
欢迎关注~~~~
对于一些逻辑稍微复杂的程序,很难避免出现在不某个类中无法访问另一个类所持有的引用。这样也就导致了编程的灵活度下降,尽管可以再次创建新的引用,也会浪费资源,甚至达不到要求。下面我来句一个例子:
比如,后台的模板文件有两个。admin_bar.html,和admin_comment.html。我现在有两个类,分别是adminAction.class.php,和adminCommentAction.class.php。admin_bar.html文件就是我们通常看到的后台管理的工具栏(通常在左边),admin_comment.html是每个工具功能项(评论)所对应的内容。如下图所示:
这样,我们在adminAction控制器类中先用模板引擎处理好admin_bar.html文件,完了根据url或表单传进来的参数进入到adminCommentAction控制器类。代码示例:
1 <?php
2 class adminAction{
3
4 private $smarty = null;
5
6 public function _construct(){
7 $this->smarty = new Smarty();
8
9 }
10
11 private function show(){
12 $this->smarty->dispose('admin_bar.html');
13 if($_GET['action'] == 'comment'){
14 new adminCommentAction();
15 }
16 if(){
17 //...
18 }
19 return;
20 }
21 }
22
23 class adminCommentAction{
24 public function _construct(){
25 //???
26 }
27 }
那么,到代码执行到adminCommentAction中时,就无法拿到adminAction中持有的smarty引用了。也许说,可以通过构造参数来传递,不过这里介绍一种更好的方式 --- 门面模式(总于进入主题了)。它能够更灵活的管理代码程序中的饮用对象。下面简单的门面模式类代码示例:
1 <?php
2 /**
3 * 对象引用管家 - 门面模式
4 */
5 class ObjectManager implements ObjectType{
6 private static $Objects = array();
7
8 public static final function get_object($key){
9
10 if(array_key_exists($key, ObjectManager::$Objects)){
11 return ObjectManager::$Objects[$key];
12 }
13 return FALSE;
14 }
15
16 public static final function set_object($key, $Object){
17 if(!array_key_exists($key, ObjectManager::$Objects)){
18 ObjectManager::$Objects[$key] = $Object;
19 return TRUE;
20 }
21 return FALSE;
22 }
23
24 public static final function clear_object($key){
25 if(array_key_exists($key, ObjectManager::$Objects)){
26 unset(ObjectManager::$Objects[$key]);
27 return TRUE;
28 }
29 return FALSE;
30 }
31 }
当然,最好给ObjectManager写一个接口类,其中存一些引用的类型,以便处理。
<?php
/**
* 全局对象引用类型常量接口
*
*/
interface ObjectType{
/**
* 后台控制器adminAction所持有的Smarty引用对象,其用于相应模板文件的模板引擎动作。
*
*/
const ADMINACTIONENGIEN= 'AdminActionEngien';
}
那么这个时候就可以这样灵活的运用了,代码示例:
1 <?php
2 class adminAction{
3
4 private $smarty = null;
5
6
7 public function _construct(){
8 $this->smarty = new Smarty();
9 ObjectManager::set_object(ObjectManager::ADMINACTIONENGIEN, $this->smarty);
10 }
11
12 private function show(){
13 $this->smarty->dispose('admin_bar.html');
14 if($_GET['action'] == 'comment'){
15 new adminCommentAction();
16 }
17 if(){
18 //...
19 }
20 return;
21 }
22 }
23
24 class adminCommentAction{
25 private $smarty = null;
26 public function _construct(){
27 $this->smarty = ObjectManager::get_object(ObjectManager::ADMINACTIONENGIEN);
28 $this->smarty->require_file();//这个函数可能smarty没有,因为我用的引擎是自己写的
29 $this->smarty->assign();
30 $this—>smarty->display();
31 }
32 }
|
|
|