【问题标题】:Passing properties from parent controller to child controller in Kohana 3在 Kohana 3 中将属性从父控制器传递到子控制器
【发布时间】:2011-02-22 22:19:36
【问题描述】:

我正在使用 Kohana 3 并使用名为 controller_Facebook 的中间控制器,它从 Controller_Template 扩展,然后从 Controller_Facebook 扩展 Controller_Home。我在 Controller_Facebook 中设置了两个属性并尝试在 Controller_Home 中使用它们,但它在那里不可用。它给出空值。我的代码类似于以下:

class Controller_Facebook extends Controller_Template{

        public $template='template';
        public $facebook;
        public $session;

    public function __contstruct(){
        include_once(dirname(__FILE__)."/facebook_class.php");
            global $facebook;
            $facebook = new Facebook(array(
              'appId'  => 'xxxxxxxxxxx',
              'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
              'cookie' => true,
            ));
            $this->facebook=$facebook;
            $this->session = $facebook->getSession();
    }
}

然后在 Home_Controller 中:

  class Controller_Home extends Controller_Facebook{


        public function  __contstruct() {
                parent::__contstruct();

        }



        public function action_index()
    {
                global $facebook;
        $this->template->content=new View('home');
        $this->template->selected='home';   var_dump($this->facebook);
                $this->template->app_id='123';

                var_dump($facebook);

                $this->template->session=$this->session;

    }

}

此外,如果我在父类中回显某些内容,则它不会输出该内容。它也在 facebook 中工作,这是否意味着我的父构造函数正在工作?我认为它正在工作。如果有人认为我做错了什么,请告诉我。

【问题讨论】:

    标签: php model-view-controller kohana kohana-3


    【解决方案1】:

    不要不要盲目地超载__construct,它会破坏你的控制器。您应该在 before() 方法中执行此操作。完成后请务必致电parent::before()

    而且global 的东西是完全没有必要的。只需设置$this->facebook,稍后使用$this->facebook 访问即可。

    【讨论】:

    • 之前我需要做什么?你的意思是我需要定义一个 before 方法并在其中做 parent::before 吗?或者我需要在我在 controller_facebook 的构造函数中做的事情之前做这些事情?你能澄清一下吗
    • 哦,谢谢,这行得通,非常感谢,也感谢 stackoverflow :)
    【解决方案2】:

    你拼错了__construct。

    此外,如果您已将全局设置为类属性,则无需访问它。

    只需访问它

    $this->facebook
    

    【讨论】:

    • 哦,是的,我犯了什么严重错误
    • 通过更正它现在说这个错误:ErrorException [致命错误]:调用非对象上的成员函数 body() 它在此处显示错误:public function after() 41 { 42 if ($this->auto_render === TRUE) 43 { 44 $this->response->body($this->template->render()); 45 } 46 在 SYSPATH/classes/kohana/controller/template.php [44] 47 return parent::after(); 48}
    • 这是因为你的构造函数。将其代码移动到公共函数 before() 并且不要忘记添加 parent::before() 调用。
    【解决方案3】:

    IMO,最好为 FB 类创建 Kohana 包装器,然后在您的控制器中使用它。像这样:

    $this->facebook = Facebook::instance(); // wrapper will automatically load config with appId etc
    $this->session = $this->facebook->get_session();
    

    附言。可能是 Kohana 已经有这个实现了吗?类似https://github.com/zombor/Kohana-Facebook

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      • 2020-05-29
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      相关资源
      最近更新 更多