【问题标题】:How to check the condition before reading any method in the Controller in Codeigniter?如何在 Codeigniter 中读取控制器中的任何方法之前检查条件?
【发布时间】:2019-07-02 10:52:13
【问题描述】:

如何在读取控制器中的所有方法之前检查条件。检查条件后,如果为 TRUE,则只有控制器中的方法必须可访问。如果条件返回 false,则应将其重定向到另一个控制器。我怎样才能做到这一点?

提前致谢。

【问题讨论】:

  • 您可以将您的条件放在控制器上的public function __construct() { parent::__construct(); } 中,如果它是真的,那么它将允许您访问控制器中的所有功能。
  • 看一个例子会很有帮助。
  • @Rosahn ,这个对我有用。公共函数 __construct() { parent::__construct();但是,它仅基于会话数据工作。
  • 您可以使用钩子或创建自己的控制器并扩展它来实现此目的。
  • @ShubhamAzad ,是的。它也对我有用。非常感谢。

标签: php codeigniter controller conditional-statements


【解决方案1】:

控制器在每次初始化时自动运行构造,在它运行任何其他方法之前,因此您可以使用它来设置访问其他控制器方法所需的条件。

例子:

class ExampleController extends CI_Controller {

   public function __construct () {

       // use construct method of CI_Controller(the parent)
       // don't foget this because it wont work without it!
       parent::__construct();


       if(true) {
           //do the thing you want
       } else {
          // use the url helper to redirect to another page/controller
          $this->load->helper('url');
          redirect('another-page');
       }

   }

   public function index() {
      //display index page...   
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 2012-06-09
    相关资源
    最近更新 更多