14

I'm writing a plugin for which I'd like to be able to set site-wide preferences via custom variables in config.php (eg $['myplugin_config_item']), and have those variables available in all my plugins methods, eg:

...
class Myplugin {

  public $return_data;

  function Method(){
    //how do I access $['myplugin_config_item'] here?

  }
  function Method2(){
    //and if I want to access $['myplugin_config_item'] here too, what's the most efficient way to do so?
  }

}
...

What's the cleanest/neatest way to do this?

2 Answers 2

20

If you need to access a variable repeatedly then you should generally place it within a constructor method and assign it as a class property, rather than continuously checking config values. This approach also gives you the opportunity to set a default value which you can use class-wide if the config item is not found.

<?php
class Myplugin {

    var $return_data;
    var $my_setting;

    function __construct()
    {
        $this->EE =& get_instance();

        if($this->EE->config->item('my_setting') !== false)
        {
            $this->my_setting = $this->EE->config->item('my_setting');
        }
        else
        {
            $this->my_setting = "Default value if config value doesn't exist.";
        }
    }

    function one()
    {
        echo $this->my_setting;
    }

    function two()
    {
        echo $this->my_setting;
    }

}
8

Since ExpressionEngine is based on Codeigniter, you can use the CI Config class to fetch config items.

http://codeigniter.com/user_guide/libraries/config.html

class Myplugin {

    public $return_data;

    function Method()
    {
        $this->EE =& get_instance();

        $item = $this->EE->config->item('myplugin_config_item');
    }

    function Method2()
    {
        $item = $this->EE->config->item('myplugin_config_item');
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.