Advertisement
  1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Semi-protected methods

Comments in 'Resources' started by Falk, Dec 24, 2014.

  1. Falk
    Offline

    Falk Staff Member Global Moderator

    Joined:
    Sep 2, 2013
    Posts:
    1,707
    Plugins:
    22
    Minecraft User:
    Falkirknh
    This is bad practice and you should be very sure before you implement it.

    The preamble
    When I was writing Volt I ran into a problem. I had a method called getVoltServer which would return a ServerTask object, if another plugin used this they could have direct and unrestricted access to the server thread. My goal wasn't to prevent that, but to make sure that the access went through a very basic intermediary layer for security and logging (that way if the plugin could be blocked at any time). If I didn't implement this, plugin developers would be tempted to use the method directly to avoid dealing with the extra layer. What I needed was a way to make the method only available inside my plugin and not to any other plugins.

    The code
    You can use this code to make a method only accessible to calling contexts in the same namespace.
    PHP:
    public function scaryFunction(){
            
    $trace debug_backtrace();
            if (isset(
    $trace[1]) && explode("\\"$trace[1]['class']) === __NAMESPACE__) {
                 
    // Do function stuff
            
    }
            else{
                 throw new \
    Exception("Method is only for internal use");
            }
    }
    You can minify this down to (untested):
    PHP:
    public function scaryFunction(){
            if (!(isset((
    $trace debug_backtrace())[1]) && explode("\\"$trace[1]['class'])[0] === __NAMESPACE__)) throw new \Exception("Method is only for internal use");
            
    // Do function stuff
    }



    (Yes, smart people, I do know that Reflection can circumvent this, my goal was to make it easier to use the system I provided than accessing the object directly)
    Last edited: May 2, 2015
  2. PEMapModder
    Offline

    PEMapModder Notable Member Plugin Developer

    Joined:
    Oct 9, 2013
    Posts:
    7,306
    Plugins:
    11
    Minecraft User:
    PEMapModder
    In simple words, "class-private".
    CrazedMiner and Falk like this.

Share This Page

Advertisement