We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 45063
    • 40 Posts
    Lets say I have some Controller class in a snippet:

    class Controller {...}
    $ctrl = new Controller();
    


    At the bottom of this snippet, I have a switch which controls what method I need to launch:

    switch($scriptProperties['action']) {
        case 'do':
            return $ctrl->doSomething();
            break;
        ...
    }
    


    The thing is, this snippet must be called multiple times on a page. Which means I have to check if such class doesn't already exists (not a big problem, thou) AND creating a new instance of this class each time.

    Is there any better way to do such things? Thanks in advance.


    This question has been answered by roman.khazizov. See the first response.

      • 3749
      • 24,544 Posts
      The best option is to make doSomething() a static method and call it with:

      return Controller::doSomething();


      Then there's no need to instantiate the class.

      This may not be possible, depending on what the controller does, because you can't use $this to access class variables in a static method.
        Did I help you? Buy me a beer
        Get my Book: MODX:The Official Guide
        MODX info for everyone: http://bobsguides.com/modx.html
        My MODX Extras
        Bob's Guides is now hosted at A2 MODX Hosting
      • discuss.answer
        • 45063
        • 40 Posts
        Quote from: BobRay at Mar 03, 2016, 02:48 PM

        This may not be possible, depending on what the controller does, because you can't use $this to access class variables in a static method.

        That's why I ended up using singleton pattern. This might actually solve the problem:

        public static function getInstance()
            {
                if (null === static::$instance) {
                    static::$instance = new static();
                }
                
                return static::$instance;
            }


        This way it should instantiate a class only once.
          • 3749
          • 24,544 Posts
          That looks like a good solution. smiley
            Did I help you? Buy me a beer
            Get my Book: MODX:The Official Guide
            MODX info for everyone: http://bobsguides.com/modx.html
            My MODX Extras
            Bob's Guides is now hosted at A2 MODX Hosting