You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CodeIgniter的CI_Controller引用对象上新增Setter/Getter方法?

Adding Setter/Getter Methods to CI_Controller via Hook

Got it, let's walk through how to add the setter and getter methods you need to your CodeIgniter controller instance using the hook you've already started building. Here's a practical implementation that fits your existing code structure:

Step 1: Update Your Response Hook Class

We'll modify the init() method to dynamically attach the setter and getter methods to the CI controller instance. We'll use PHP closures (and bind them to the CI instance so $this behaves correctly):

class Response {
    public function init() {
        // Grab the CI instance
        $this->CI =& get_instance();
        
        // Initialize the response array as you already did
        $this->CI->response = array(
            'content'=> null,
            'status' => 'ok',
            'errorMessage' => null
        );

        // --- Add Getter Methods ---
        // Generic getter to fetch the full response or a specific key
        $this->CI->getResponse = function($key = null) {
            if ($key === null) {
                return $this->response;
            }
            return isset($this->response[$key]) ? $this->response[$key] : null;
        };
        // Bind the closure to the CI instance so $this points to the controller
        $this->CI->getResponse = $this->CI->getResponse->bindTo($this->CI, get_class($this->CI));

        // Specific getter for content
        $this->CI->getContent = function() {
            return $this->response['content'];
        };
        $this->CI->getContent = $this->CI->getContent->bindTo($this->CI, get_class($this->CI));

        // --- Add Setter Methods ---
        // Generic setter to update single keys or bulk update via array
        $this->CI->setResponse = function($key, $value = null) {
            if (is_array($key)) {
                foreach ($key as $k => $v) {
                    if (isset($this->response[$k])) {
                        $this->response[$k] = $v;
                    }
                }
            } else {
                if (isset($this->response[$key])) {
                    $this->response[$key] = $value;
                }
            }
            return $this; // Enable method chaining
        };
        $this->CI->setResponse = $this->CI->setResponse->bindTo($this->CI, get_class($this->CI));

        // Specific setter for content
        $this->CI->setContent = function($content) {
            $this->response['content'] = $content;
            return $this; // Enable method chaining
        };
        $this->CI->setContent = $this->CI->setContent->bindTo($this->CI, get_class($this->CI));
    }
}

Step 2: Verify Hook Configuration

Make sure your hook is properly registered in application/config/hooks.php to run after the controller constructor:

$hook['post_controller_constructor'] = array(
    'class'    => 'Response',
    'function' => 'init',
    'filename' => 'Response.php',
    'filepath' => 'hooks',
    'params'   => array()
);

Step 3: Use the Methods in Your Controllers

Now you can call these methods directly from any controller that extends CI_Controller:

class Home extends CI_Controller {
    public function index() {
        // Set content using the specific setter
        $this->setContent('Welcome to my CodeIgniter app!');
        
        // Or use the generic setter to update multiple values at once
        $this->setResponse(array(
            'status' => 'warning',
            'errorMessage' => 'This is a test warning'
        ));

        // Fetch content
        $pageContent = $this->getContent();
        
        // Fetch the full response array
        $fullResponse = $this->getResponse();
    }
}

Key Notes:

  • Binding Closures: We use bindTo() to ensure the closure's $this references the CI controller instance, not the Response hook class.
  • Flexibility: The generic setResponse() and getResponse() methods work for any key in your response array, while the specific methods (like setContent()) provide more readable shorthand for common fields.
  • Chaining: Returning $this from setters lets you chain calls (e.g., $this->setContent('Hi')->setResponse('status', 'success');).

内容的提问来源于stack exchange,提问作者i.brod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:36:10