markjaquith / feedback

Ask @markjaquith anything!
42 stars 4 forks source link

Question regarding the visibility of methods called via add_action() and add_filter() within a class #35

Closed MickeyKay closed 9 years ago

MickeyKay commented 9 years ago

When developing plugins, I often run into the issue where I'll be adding an action/filter from within a class like so:

add_action( 'plugins_loaded', array( $this, 'my_function' );

Because my_function() is being hooked to an action, I have to define it as public in order to keep it accessible (or use some workarounds that seem not so great, e.g. http://stackoverflow.com/a/22426996).

Oftentimes, however, this type of function that I don't want publicly accessible. I'm not super concerned with someone digging into the code and realizing they could call these functions, but it just seems like best practice to hide all methods that aren't part of the public-facing interface.

Any thoughts on whether this is a big deal or not? Solutions? How do you deal with this issue?

Thanks Mark!

JDGrimes commented 9 years ago

My two cents:

I know it isn't your main concern, but it isn't possible to prevent someone from calling your methods if they really want to. (That goes for private methods, too: they can always use reflection.) If you want to limit the way the methods are called, you might use current_filter() in each one to check that the method is being called during the correct action/filter. It's possible to fake the current filter, but it would have to be deliberate.

Kind of related question on WPSE: http://wordpress.stackexchange.com/q/155488/27757

MickeyKay commented 9 years ago

Got it, thanks JD.

On Saturday, August 2, 2014, J.D. Grimes notifications@github.com wrote:

My two cents:

I know it isn't your main concern, but it isn't possible to prevent someone from calling your methods if they really want to. (That goes for private methods, too: they can always use reflection.) If you want to limit the way the methods are called, you might use current_filter() in each one to check that the method is being called during the correct action/filter. It's possible to fake the current filter, but it would have to be deliberate.

Kind of related question on WPSE: http://wordpress.stackexchange.com/q/155488/27757

Reply to this email directly or view it on GitHub https://github.com/markjaquith/feedback/issues/35#issuecomment-50976686.

markjaquith commented 9 years ago

Yeah, you have to make them public. It’s just one of those things. I don't think it’s a big deal.