能不能在controller对象的构造函数里设定一个smarty对象的属性

#1 stalker

class main extends spController{
    //需要一个smarty对象的style属性

    public function index(){
        $this->display($this->style.'/'.$__controller.'/'.$__action.'.html');
    }
}

2010-03-10 11:20:10

#2 jake

构造函数是__construct,如果需要在控制器的构造函数里面获取smarty对象并进行操作,可以用$this->getView()来获取。

2010-03-10 11:28:55

#3 stalker

public function main extends spController{
    public function __construct(){
        $smarty = $this->getView();
        $smarty->style = 'blue';
    }
}



提示:

Fatal error: Call to a member function getView() on a non-object

2010-03-10 16:06:17

#4 jake

要注意,在使用控制器或者模型类的构造函数,一定要加上parent::__construct();

public function main extends spController{
    public function __construct(){
         parent::__construct();
        $smarty = $this->getView();
        $smarty->style = 'blue';
    }
}

参见微博实例的general控制器的构造函数

2010-03-10 16:33:27

#5 stalker

对OO了解不够深刻  构造函数不是在实例化类的时候就会执行的吗  怎么还要在函数中调用一下自身?
另外这样在别的函数中还是无法调用该属性

class main extends spController{
    public function __construct(){
        parent::__construct();
        $smarty = $this->getView();
        $smarty->style = 'blue';
    }
    public function index(){
        echo $this->style;
    }
}

2010-03-11 09:48:00

#6 stalker

哦  明白了  parent代表的是spController对象  但为什么还是输出不了呢?

2010-03-11 10:22:36

#7 jake

$smarty->style = 'blue';

这是什么?smarty对象没有style这个成员变量吧?你要用$this->style

2010-03-11 10:30:25

#8 stalker

class main extends spController{
    public function __construct(){
        parent::__construct();
        $this->style = 'blue';
    }
    public function index(){
        echo $this->style;
    }
}


还是不行

2010-03-11 10:56:35

#9 stalker

class main extends spController{
    public $style = '';
    public function __construct(){        parent::__construct();
        $this->style = 'blue';
    }
    public function index(){
        $this->display($this->style.'/'.$__controller.'/'.$__action.'.html');
    }
}
这样可以了  但是在模板文件中使用变量没办法显示:
<{$style}>
输出为空

2010-03-11 10:59:49

#10 jake

这样可以了  但是在模板文件中使用变量没办法显示:

输出为空
stalker 发表于 2010-3-11 10:59
可以参考一下winblog微博实例的geranel控制器,里面有非常多的模板变量的辅助之类的操作,很有参考价值。

2010-03-12 11:01:56

#11 stalker

必须建一个spController的子类 再把各种类作为这个子类的子类才能实现吗

2010-03-15 09:37:51

#12 jake

PHP只能做到继承单个类。

OOP本身有个很重要的理念就是,在纯OOP中不推荐有“全局”的东西,但是考虑到“全局”的方便,所以在OOP中使用了父类的方式来替代全局。这里spController代表的是控制器的功能父类,而派生的这个子类general是用户级的父类,其他用户级的控制器都将继承于这个用户级的父类。

2010-03-15 10:03:00