【问题标题】:Load a controller into an other controller in cakephp将一个控制器加载到 cakephp 中的另一个控制器中
【发布时间】:2010-05-19 09:28:23
【问题描述】:

我正在开发一个 Web 应用程序,使用多个页面,每个页面都有自己的控制器。

现在的问题是控制器中有一些变量是为一个页面创建的,而这些变量是另一个页面所必需的(使用不同的控制器)。

因此我需要将一个控制器加载到另一个控制器中。

我通过添加来做到这一点 App::import('Controller', 'sections');

$sections=新的sectionController; $sections->constructClasses();

到控制器,但这似乎不起作用..

也许你们有什么想法?

提前谢谢!

【问题讨论】:

    标签: php cakephp controller


    【解决方案1】:

    我认为你对MVC architectural pattern有一些误解。如果你的枪需要一些子弹,就拿子弹本身吧,不需要用它再买一把枪。所以我希望你能理解加载控制器真是个坏主意。

    此外,如果您希望所有控制器都可以访问某些变量,例如 Gaurav Sharma 提到,您可以使用Configure::write()将数据存储在应用程序的配置app/config/core.php.e.g

    Configure::write('somekey',$someval);
    

    那么你就可以在任意控制器中通过Configure::read('somekey')得到$someval

    【讨论】:

      【解决方案2】:

      您可以使用以下任何一种方法来访问 cakePHP 应用程序中任何位置的变量。
      1.) 使用 configuration class
      2.) 对这些变量使用会话

      【讨论】:

        【解决方案3】:

        我今天早上一直在处理这个问题。我实际上是从数据库中获取控制器名称,但我已将其更改为使用变量。

        $controller_name = "Posts"; // the name of the controller.
        $action = "index"; // The action we want to call.
        
        App::import('Controller', $controller_name); 
        
        // Now we need the actual class name of the controller.
        $controller_classname = $controller_name . 'Controller'; 
        
        $Controller = new $controller_name;
        $Controller->variable_name = "something"; // we can set class variables here too.
        
        // Now invoke the dispatcher so that it will load and initialize everything (like components)
        $d = new Dispatcher();
        $d->_invoke($Controller, array('pass'=> '', 'action' => $action));
        
        // And exit so it doesn't keep going.
        exit(0);
        

        老实说,我并没有费心弄清楚“通过”是什么意思(我假设变量),但没有它会引发警告。 您还需要在您的$action 中显式调用$this->render

        【讨论】:

        • pass 是控制器中 passedArgs 变量的一半。如果你使用 Dispatcher::dispatch() 而不是 _invoke,它会为你设置这些,除了做其他可能有用的事情(但对你的目的来说也可能不必要)。
        猜你喜欢
        • 1970-01-01
        • 2011-02-26
        • 1970-01-01
        • 1970-01-01
        • 2016-04-22
        • 1970-01-01
        • 2017-12-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多