将代码添加到另一个控制器的功能

时间:2018-12-28 12:26:55

标签: php codeigniter

在CodeIgniter框架中,我有两个控制器文件: controllerA.php和controllerB.php

我需要controllerB.php在controllerA.php函数中添加代码

我不知道该怎么做,我检查了Codeigniter手册,google和stackoverflow,但找不到解决方法

controllerA.php具有功能:

function get_permission_conditions()
{
    return do_action('staff_permissions_conditions', [
        'contracts' => [
            'view'     => true,
            'view_own' => true,
            'edit'     => true,
            'create'   => true,
            'delete'   => true,

]);
}

我希望controllerB.php与controllerA.php通信并添加自定义代码示例:

function get_permission_conditions()
{

//Code from controllerA.php
    return do_action('staff_permissions_conditions', [
        'contracts' => [
            'view'     => true,
            'view_own' => true,
            'edit'     => true,
            'create'   => true,
            'delete'   => true,

//custom code from controllerB.php goes here

]);
}

2 个答案:

答案 0 :(得分:0)

您应该像这样扩展controllerA

class controllerA extends CI_Controller{
    // All the function will go here
    return do_action('staff_permissions_conditions', [
        'contracts' => [
            'view'     => true,
            'view_own' => true,
            'edit'     => true,
            'create'   => true,
            'delete'   => true,

    ]); 
}
class controllerB extends controllerA{
    public $permission_array;
    function __construct() {
        $this->permission_array = $this->do_action();  // Here $permission_array will have the array returned by controllerA's function 'do_action'
    }

    //custom code from controllerB.php goes here
    // You can use $permission all over
}

答案 1 :(得分:0)

分别为和创建一个父控制器,并让它们都扩展该父对象并将该方法移至该父对象,然后让父对象扩展CI_Controller ..非常类似于您对MY_Controller所做的操作。 ..

那是您的C_Controller(父控制器):

class C_Controller extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    // your methods that will be extended
    ...

}

那是您的A_Controller:

class A_Controller extends C_Controller
{
    public function __construct()
    {
        parent::__construct();
    }
}

那是您的B_Controller:

class B_Controller extends C_Controller
{
    public function __construct()
    {
        parent::__construct();
    }
}
相关问题