What’s The Proper Way To Instantiate a WordPress Plugin?

When it comes to plugin development – be it either widgets or plugins – there are several different ways in which we can instantiate a WordPress plugin.

Unfortunately, you’re likely to get a different answer depending on who you ask, or what you read.

Case in point: According to the WordPress Codex, instantiating a WordPress widget is done like this:

add_action( 'widgets_init', create_function( '', 'register_widget( "foo_widget" );' ) );

But I know several people who are adamantly against using create_function.

Though I personally don’t have a problem with it, I’m always interested in hearing others’ approach to how they do it and why.

So in this post, I thought I’d lay out the various ways to instantiate a WordPress plugin, pros and cons of each, but also ask each of you what your favorite method is and why.

Instantiate a WordPress Plugin

Since WordPress plugins can be divided into plugins or widgets, I’m laying out each one individually as well as the problems that I’m aware of for each of the approaches.

Note that each of the following examples is based on object-oriented programming techniques. If you’re using hooks and functions, then this doesn’t necessarily apply.

Plugins

Assuming that you have a plugin called Foo_Plugin, it’s relatively common to see this as the last line in the plugin file:

new Foo_Plugin();

I’m guilty of doing this, but the problem is that you’re essentially creating an orphaned object. You have no way to actually access it once it’s been instantiated.

The next way that others go about resolving this is to store an instance in the $GLOBALS collection. For example:

$GLOBALS['foo-plugin'] = new Foo_Plugin();

In this case, you can always retrieve a reference to the plugin, but some may argue that you’re polluting the $GLOBALS collection which, depending on the size of your plugin, could be a problem, and you may accidentally overwrite an existing plugin or value that’s stored if you’re not careful for the key that you use.

Widgets

I hit on this in the introduction to the post, but arguably the most common way to to instantiate a widget is by doing the following:

add_action( 'widgets_init', create_function( '', 'register_widget( "foo_widget" );' ) );

Again, the problem is that some developers generally don’t like using anonymous function calls via create_function to do this. The most common argument I’ve heard against this is performance.

Personally speaking, I’ve used this method since it’s what’s provided in the Codex and I’ve never really seen a performance hit.

But What About You?

And there you have it – the most common ways I’ve seen to instantiate a WordPress plugin or widget.

But I’m genuinely looking for some feedback – because I know you guys have it – on best practices not only to clarify this issue, but to improve what I do on a day-to-day basis, as well.

83 Comments

I personally follow the singleton pattern whenever I instantiate a plugin.

See:
http://eamann.com/tech/making-singletons-safe-in-php/
http://eamann.com/tech/the-case-for-singletons/

Yet still I think that classing plugins is partiall OOP due to restrictions with add_filter and add_action that can’t be called from the private methods, which makes the whole inheritance a bit harder. Though it’s offtopic :P

Regards,
Rafal

    I’m actually a fan of singletons myself and use them in client projects. The thing is that this – along with various other design patterns – aren’t often discussed in the context of WordPress development (which is a shame – perhaps a topic for another post, huh?).

    Yet still I think that classing plugins is partiall OOP due to restrictions with add_filter and add_action that can’t be called from the private methods

    You’re absolutely right. This is one of the most frustrating aspects of writing plugins in an OOP fashion simply because you can’t truly encapsulate data the way that OOP principles typically dictate.

    That said, I do try to keep my helper methods private and setup my public methods to be as small as possible and they make calls into the private methods.

    This is largely based on the SOLID principles, but – like you – this is a bit off topic. Perhaps topic for another post :).

      That’d be a good post to talk about forever as well ;)

      writing plugins in an OOP fashion

      One of my recent pet-peeves has been people who have written about developing plugins using classes for namespaces as “writing plugins in an OOP fashion.” When I’ve seen it done it’s usually an oversight where the author knows better, but I think it does a disservice for those who do not yet know OOP because it cab make them think that class-based namespacing is OOP, which of course it’s not.

      As I know you know since you’ve got better educational credentials on the subject of computer science than I! :)

        When I’ve seen it done it’s usually an oversight where the author knows better, but I think it does a disservice for those who do not yet know OOP because it can make them think that class-based namespacing is OOP, which of course it’s not.

        Wait, wait, wait. You want me to read between the lines, but now you won’t? ;P

        In all seriousness, you know know what I mean, though. And you’re right – people do represent OOP in a fashion that doesn’t really do the paradigm the service it deserves.

        If it’s in the context of WordPress, this may go back to Rafal’s previous comment about how we can’t write true OOP code because of the nature of the hook system, but, then again, it may also have to do with such a low barrier of entry into development for WordPress (or PHP) that people get away with doing things they should be doing a better job of doing.

        As I know you know since you’ve got better educational credentials on the subject of computer science than I!

        Maybe. You’ve got experience++ which counts significantly more, I think.

          If it’s in the context of WordPress, … how we can’t write true OOP code because of the nature of the hook system…

          Two points on that:

          1.) WordPress’ hook system is an example of event-drive programming (EDP) although I (almost?) never hear anyone describe it that way (probably because most WordPressers are not CS grads. :-)) In the Wikipedia History section for OOP they say:

          OOP toolkits also enhanced the popularity of event-driven programming (although this concept is not limited to OOP). Some feel that association with GUIs (real or perceived) was what propelled OOP into the programming mainstream.

          So I think people who criticize WordPress for lack of OOP often do so without acknowledging that OOP and EDP are not mutually exclusive and that EDP is itself a valid paradigm. In general EDP makes extension easier whereas OOP enables enforcing architecture easier; EDP is more flexible and OOP more rigorous. Visual Basic was initially popular with “accidental” programmers just like WordPress in large part because of EDP and because one didn’t have to learn nearly as much as a C++ or PHP MVC framework programmer before they could become initially productive. And there’s an awful lot of societal value in that initial productivity.

          2.) Again, be careful not to give the wrong impression; it is completely possible to write true OOP code in one’s own plugin, but because of the event-driven paradigm it’s just not possible to have one’s plugin be completely OOP (assuming there was an actual quantitative definition of completely OOP, but we both know what we mean when we say it. :)

          A lot of the plugins I write use classes that follow standard OOP practices although some of them violate standard OOP practices by design, for ease of extensibility; i.e. I have a set of classes in one library where you subclass only the main class and are allowed to extend the other classes from that one subclass; OOP purists would shudder, but IMO it works well.

          Yes, you can’t get around using hooks in WordPress and hooks are not pure OOP per se but that doesn’t mean you can’t write your own classes in fully OOP style although I don’t think that doing so 100% of the time is actually the best choice, all things considered.

            If it’s in the context of WordPress, … how we can’t write true OOP code because of the nature of the hook system…

            I should clarify, because you’re right about EDP – and this is something I’ve shared with people at meetups and other conversations (among other things like Pub/Sub, Template Method, etc), but my rub against “true” OOP is that because of the hook system, certain methods that I believe should be private can’t be marked as such because they need to be publicly accessible.

            The natural pushback, of course, is that if I’m trying to mark a function as private but can’t because of the architecture of the foundation on which the system is built, then perhaps I’m organizing my code incorrectly.

            But the way I see it is this:

            public methods should be accessible by not only the system in which they exist, but by third-party callers, as well. Namely, other developers.
            With the hook system, I have to mark a function as public in order for WordPress to properly call it but this means that anyone can come along, instantiate the class, and then call those public methods on it which really how it should be.

            All that aside, I really do like the EDP paradigm because it’s so simple: An event is raised and if a function is registered with it, then it’s fired. It doesn’t get much simpler. I just wish there was better encapsulation.

            Finally, there are strategies around this: If there’s some type of critical functionality that you don’t want third party developers calling, then you can wrap it into a private function and call it within the context of the public function so long as said public isn’t just a wrapper for a private function. Then things are just getting silly.

            But thanks for this. Now I feel like an architecture astronaut and that’s the complete opposite of what I’ve wanted ;P.

              my rub against “true” OOP is that because of the hook system, certain methods that I believe should be private can’t be marked as such because they need to be publicly accessible.

              Ah, yes. I have had that issue to, but it hasn’t bothered me terribly.

              I used the convention of a leading underscore on private and protected methods so if someone uses them they are kind of on their own. But it would definitely be nicer if we could disable access.

              Now you are making me think about it, about how I would handle this if I truly wanted to ensure that those kind of methods are true and well hidden. Hmm. i’m sure it could be done by adding a bit of runtime overhead though not sure that would be worth it?

              Now I feel like an architecture astronaut and that’s the complete opposite of what I’ve wanted ;P.

              Interesting. That’s the first I’ve seen of that joelrant. But it seems to be more about companies jumping on “the next big thing” where there is no clear use-case rather than about pedantic programmer debates. Still I guess it can apply to pedantic programmer debates, and I’ve probably have a few too many of them in my career.

              Architecture is a good thing if it has a tangible benefit like Joel pointed out, such as REST for example. But now that you mention it I do find myself defending architecture choices when I am trying to make another point far more than criticizing other’s architecture choices, at least in the blogosphere that is. Wish I didn’t have to do that. :)

                Ah, yes. I have had that issue to, but it hasn’t bothered me terribly.

                I teeter on this a lot. To me, it’s a matter of wanting to leverage OOP principles and features but also knowing that 99% of the calling is going to come from WordPress rather than a third-party client (be it a person or another library).

                Still, there’s something inside of me that still doesn’t feel “right” about having to declare methods as public just to get them registered with the right event.

                That’s probably a weak argument, but it’s the best I’ve got. For now, at least :).

                I used the convention of a leading underscore on private and protected methods so if someone uses them they are kind of on their own.

                I used to do this when I was writing a lot more vanilla JavaScript even though it’s possible to write private functions.

                But here’s the thing with that. If you’re to break down what you’re doing to a beginner, you’d basically be saying: “Yes, the access modifier says public but the underscore indicates that it should be private.” o_O

                Then I suppose you’d continue: “The truth of the matter is that the reason we have to do that is because although this function should be marked as private since there shouldn’t be any outside access, the application on which this is function registered requires that it be public so that it can access it.”

                When then leads down an entirely different rabbit trail that’s probably better left to a face-to-face conversation than a blog comment.

                i’m sure it could be done by adding a bit of runtime overhead though not sure that would be worth it?

                Don’t say things like this, because the answer I want to give is “no, it’s not worth it,” which then has me wanting to argue the entire reason of using classes to begin with. If everything is public, what does it matter at that point…?

                Joking :).

                But in all seriousness, this is one of those things that differs in practice – at least in the WordPress-world, and even others for that matter – from OOP theory. It’s like that old quote “In theory there is no difference between theory and practice. In practice there is.” There’s perfectly valid ways to use private functions in class-based plugins such as in the case of helper methods (which are more likely to be used if you subscribe to the SOLID principles).

                And we can sit all day and talk about the academics and pedantics of OOP, but at the end of the day we need to strike a balance between doing good work and shipping quality code. It’s tough when we want to make sure we’ve got the perfect solution though, isn’t it?

                Finally, Joel’s article may be more about companies jumping on to the next big thing, but it still hits on the idea of software architects who spend more time whiteboarding the perfect solution to a problem for hours on end rather than getting a functioning thing. I’m a firm believer that discovery can come just as much, or actually more so, during the development process rather than on the frontend.

                But now that you mention it I do find myself defending architecture choices when I am trying to make another point far more than criticizing other’s architecture choices, at least in the blogosphere that is. Wish I didn’t have to do that. :)

                Oh, you know the answer to this. Our projects our like our moms – we’re the only people free to make jokes about ‘em, but as soon as someone else does, then it’s gloves off ;).

                I rarely get into debates about this kind of stuff unless I view it something that’ll prove educational and/or fun for me. Generally speaking, conversations on this blog are both.

                But you won’t find me hopping on many other threads just to make a point that’ll be forgotten in a week or so :).

                As noted elsewhere we pretty much agree, all. :)

                One (final?) elaboration; I’ve gone through several generations of software “engineering” principles since 1987 and I’ve seen staunchly believed principles get eclipsed and replaced with other staunchly believed principles, several times over. In recent years I’ve actively experienced software that violates many accepted best practices (Drupal, WordPress and a lot of other lesser known projects) and yet by most practical metrics this “bad” software has been far more successful than “better architected” competing software.

                In Microsoft’s heyday I thought it was marketing and money that created the success but now in the era of open source I know it can’t be money. I’m left to ask myself if it is all marketing or if actually “the wrong” way is not often better and “the right” is not often worse?

                The conclusion I’ve come to is that it is execution of vision that matters and that accepted the “right” way usually optimizes for a single concern while remaining blissfully unaware of other valid concerns and their specific solutions. Thus I no longer have confidence in best practices by fiat, I can only believe there are a myriad of potentially appropriate choices each with their respective tradeoffs.

                FWIW. :)

                P.S. I really, really wish you only blogged once per week so I’d have some time to stop commenting and blog myself!

                  I’ve gone through several generations of software “engineering” principles since 1987 and I’ve seen staunchly believed principles get eclipsed and replaced with other staunchly believed principles, several times over.

                  I was just talking about this idea with John yesterday specifically around software craftsmanship.

                  Specifically, we were talking about how there is this concept of craftsmanship in order trades – such as, say, iron wielding or something similar – and how once you’ve locked in that process, it doesn’t really change.

                  But software is different: New languages emerge, the foundations and frameworks that we use grow and change, and ultimately, everything is malleable. Therefore, I’d say that software craftsmanship can, does, and obviously, will persist, but we’ll never be “there” or we’ll never be “done.”

                  There’s too much change.

                  Obviously, I’m not as far into my career as you are but there have been frameworks that I’ve moved away from simply because each new version introduced so many changes, I was spending more time reworking previous versions of software just to make it work with the new version of the framework.

                  Thus I no longer have confidence in best practices by fiat, I can only believe there are a myriad of potentially appropriate choices each with their respective tradeoffs.

                  This. +1.

                  I really, really wish you only blogged once per week so I’d have some time to stop commenting and blog myself!

                  But where’s the fun in that?!

                  Found this thread while looking for the best way to have data available to a theme – singleton or global… and reading through I thought I would add to your comment as I couldn’t agree more. I’ve been doing this coding stuff for about the same time and I have seen the ‘right’ way to do things change a few times together with the ‘wrong’ software principles coming out on top. I agree with your vision idea as ultimately it is that we are trying to create something useful not something that it is theoretically beautiful.

Hey Tom,

Do you see any particular benefit of using the $GLOBALS mechanism over static this() method that Mike Schinkel presented in his post on Using Singleton Classes for WordPress Plugins?

Thanks,
Taras

    Personally, no.

    In fact, I’m not a huge fan of using $GLOBALS, though I’m not afraid to admit that I’ve done (as evidenced by this post) it especially when needing to quickly ship something under a tight deadline (and the plugin being under more constrained conditions that, say, the plugins repository).

    When possible, I tend to default – or try to default to – good OOP practices, but, like Rafal mentioned, there are limitations to what we can do.

Reading your post I got an idea. I didn’t test it, but what Do you think?

apply_filter( 'foo_plugin_init', new Foo_Plugin() );

Maybe, with this approach you can create a filter to undo things or configure the plugin on the fly. Also, maybe this filter could be fired from within the plugin.

Would be nice if the Foo_Plugin object was designed to do and undo things.

What Do you think about?

    @Thiago – That’s a really cool idea, but it has a few flaws.

    First, it requires PHP 5.3 for support of the __invoke() method that enables a class to be callable and WordPress unfortunately still supports PHP 5.2.4. This is what that might look like:


    class Test_Callable_Plugin {
    function __invoke() {
    echo 'It worked!';
    }
    }
    add_action( 'init', new Test_Callable_Plugin() );

    Second problem is that it instantiates the class when you add the hook, so unfortunately I think it’s really no better than this:


    new Test_Callable_Plugin();

      Hi,

      it’s not necessary php 5.3. With that code I’m just giving to user an opportunity to filter the instantiated plugin and do with it what they want. They could do things like this with your plugin

      add_filter(‘foo_plugin_init’, ‘do_something_with_the_plugin_instance’);
      function do_something_with_the_plugin_instance( $plugin ) {

      $plugin->do_something();

      // and yes, you can let your user decide where he wants to save his plugin instance, like
      $GLOBALS['foo-plugin'] = $plugin;
      }

        @Thiago – Forgive me, I misread your comment. For some reason I thought you post add_filter( 'init', new Foo_Plugin() ); instead of apply_filter( 'foo_plugin_init', new Foo_Plugin() );. I guess I just immediately liked the idea I thought you proposed until I realized it wouldn’t work. Sorry for my misreading.

    Mike obviously covered this in much more detail, and as much as I dig the idea, it still basically creates an orphaned object leading us back to one of the main problems with instantiating plugins :T.

I don’t like using anonymous functions (like create_function) because it’s just not playing nice. It makes it impossible for other developers to unhook the function via remove_action() if they need to for some reason.

    It makes it impossible for other developers to unhook the function via remove_action() if they need to for some reason.

    This is a really good point that’s worth noting – hopefully other readers will see this, too as I should’ve mentioned this in the post.

    I do want to mention that I think create_function has its benefits (though this could be my JavaScript background talking :)), but it can be abused just as much as it is used.

    What is the alternative method for instantiating widgets to the create_function?

If you’re looking for a way to instantiate an instance of your class without “polluting” the global scope, I’d use the singleton (anti-)pattern, as Rafal mentioned above.

For any project I can manage it, I make PHP 5.3 a requirement and end up using namespaces and better function names; classes are only for real objects and everything else goes in a function (the exception being classes that have to extend WordPress’ own classes).

I’ve also been using non-global object providers like this:

https://gist.github.com/johnpbloch/5246966

That keeps the code scope-agnostic, easily testable, and extremely flexible. But it requires PHP 5.3, so it can’t be used everywhere.

    @John – Interesting approach. Can you add some sample code to that Gist showing it in use?

      @Mike That is some sample code! ;)

      I’ll get around to getting some real code up there some time…

        @John – Okay, I guess I wasn’t following it at first.

        So you write that level of complex code for every plugin? Wouldn’t it be better to create something reusable so that plugin developers don’t have to write code with that complexity each time they want to create a plugin? They are more likely to get it wrong if so, and I’m certain it would scare off the accidental programmers a.k.a. designers.

        Also, as coded I notice it requires PHP 5.3. IMO, at least until WordPress officially moves to PHP 5.3 I can’t see a best practice for plugin development requiring v5.3. I know you like to use the other features but IMO they are not appropriate except for custom plugins for specific sites.

        Finally, what’s the real benefit from the complexity you propose? I’m assuming you are talking about using it for the main class of a singleton plugin (which is what I think Tom’s post is about. Right Tom?) and not an arbitrary class instantiation, which is pretty much a different discussion. I can see some benefit for the latter but am struggling to see its benefit for the former?

          No, that’s not quite what I was getting at. In my first comment, my first paragraph was answering Tom’s question; there, I said a singleton is probably the best bet. I then continued to say “Here’s something I’ve been using for my own stuff that I think is kind of nifty and is a different approach to solving the same problem that singletons do, and it’s 5.3+ only, so don’t try putting this in a distributed plugin.”

          Mostly I use that approach for objects that I want to be accessible globally without making them an actual global, service providers, and DI-related stuff.

          I definitely wouldn’t suggest that as a general solution for any given use case. :)

            Mostly I use that approach for objects that I want to be accessible globally without making them an actual global, service providers, and DI-related stuff.

            You’re getting into serious stuff here. Mike and I have actually had a discussion, IIRC, about topics like dependency injection and other similar topics.

            The short of it is that I like the idea, but I hate the terminology primarily because I think that it overcomplicates a simple idea.

            This is stuff that I’d love to discuss more, but this particular thread isn’t the place – and I’m wondering if a post is too niche for it.

            We’ll see. :)

          Also, as I mentioned above, I try not to use classes for plugins unless they really are meant to be instantiated, opting rather to use namespaced functions (again, I’m talking about my personal preference for code that I know will be running in a PHP5.3+ environment). There’s nothing inherently object oriented about a WordPress plugin, so why should I force my plugins into that mold if I don’t have to?

            There’s nothing inherently object-oriented about a WordPress plugin, so why should I force my plugins into that mold if I don’t have to?

            Fair enough, and point taken. Personally, I’m a fan of OOP for a number of reasons that least of which is not how I can conceptually organize the code.

            Granted, the same case can be made for well-organized functions, but aiming for high cohesion, small, purposeful classes helps me do better work.

            But in this case, and at the risk of sounding cliche, I think it’s a matter to each his own. After all, you clearly know what you’re doing :).

          No, that’s not quite what I was getting at.

          Cool.

          namespaced functions (again, I’m talking about my personal preference for code that I know will be running in a PHP5.3+ environment). There’s nothing inherently object oriented about a WordPress plugin, so why should I force my plugins into that mold if I don’t have to?

          Interesting. Since a lot of my plugin work is targeted at the repository I constrain myself to what works in PHP 5.2.4 and since namespaces are not available there I avoid them like the plague (and truth-be-told some of it is probably my stubbornness because of how awful the syntax chosen for PHP namespaces is.)

          I’ll have to think about that approach for a while. I know when I started I used classes with static methods vs. singletons but moved away from them because of issues I discovered with the former. I can’t honestly speak to a technique unless i’ve used it for a while in practice.

          A few questions though: If you use namespaces and functions then your “container” becomes the file vs. the class. If you are coding to allow other plugins to disable your plugin’s instantiation, how would you choose to do that? Also, with namespaces you are exporting the need to understand how to call namespaced functions for anyone that might want to use one of your functions as a helper function, right? Last question: How do you handle variable state that should be encapsulated in your plugin?

          That said, maybe we should start pushing WordPress for a “Move to PHP 5.3″ campaign for users so we can get to PHP 5.3 sooner than later? :)

            Since a lot of my plugin work is targeted at the repository I constrain myself to what works in PHP 5.2.4 …

            Wait, what? I thought you avoided the repository like the plague, Mike? :)

            But more seriously: Internally, my team and I just finished working through some development standards and ultimately landed on simply using the base that WordPress supports primarily because so many budget hosts out there provide the bottom rung.

            Like John mentioned in a previous comment, if I can have more control over the environment, I’m all for using the latest-and-greatest, but if we’re aiming for a mass market product, it’s just not an option.

            and since namespaces are not available there I avoid them like the plague (and truth-be-told some of it is probably my stubbornness because of how awful the syntax chosen for PHP namespaces is.)

            As far as OOP in PHP is concerned, a lot of people complain about how things feel “tacked on.” I’ve rarely taken a stance on this, but the namespacing does.

            Personally, I like things such as:

            namespace MyNamespace {
            class MyClass {
            //..
            } // end MyClass
            } // end MyNamespace

            But that’s really neither here nor there considering it’s in as it is.

              Wait, what? I thought you avoided the repository like the plague, Mike?

              LOL! No, you misread. What I previous said I avoid repository that requires free support for non-client plugins. :)

          Yeah, I used to hate the syntax too. Then I just stopped caring about that. I just figured, “who cares? this is PHP, land of double clawed hammers!” and started using them.

          I still have an initialization function that’s hooked onto plugins_loaded (usually priority 10). Unhook that and the plugin doesn’t run.

          Yes, if someone wants to use my code in their plugin, they will need to know how to use namespaces. If they’re getting the function from a snippet online or from documentation, the point is moot, since they’re probably just copying and pasting; if they found the function by digging through source code, I have confidence they can figure namespaces out. :)

          I’m not sure I understand the question about variable state encapsulated within the plugin. Care to elaborate?

          maybe we should start pushing WordPress for a “Move to PHP 5.3″ campaign for users so we can get to PHP 5.3 sooner than later?

          Well, WP won’t do it until the numbers justify it. We should focus our efforts on hosts and users to switch to PHP 5.4 and then WP will switch. And we should have been doing that since PHP 5.3 came out.

          I’m assuming you are talking about using it for the main class of a singleton plugin (which is what I think Tom’s post is about. Right Tom?) and not an arbitrary class instantiation, which is pretty much a different discussion.

          Yep – I think that this discussion has ended up providing some seriously good conversation (and neat approaches to development) – though I was initially just asking about the main class of a plugin.

          But don’t take this as me dissuading conversations like this! They’re fun and, honestly, I’m digging learning how everyone is approaching this because there’s clearly a variety of strategies we’re all using.

        I have confidence they can figure namespaces out.

        Approaches to coding, like so many things, are driven in large part by values. For me I’ve decided that making things approachable and not off-putting for the accidental programmer is a primary importance. Other’s probably care less about that.

        I’m not sure I understand the question about variable state encapsulated within the plugin. Care to elaborate?

        Background: I’ve been proposing the use of singletons class(es) for the main class(es) of a plugin; one for the general hooks, and maybe one each for the admin hooks and for the AJAX hooks if the plugins is large and complex enough to need the separation. Given that I’ve found that I always have the need for several instance variables assuming the plugin is more than trivial.

        One simple example is a variable to hold onto the hook suffix returned when you call add_submenu_page() within a plugin. Using your approach you’d have to use a global variable, right?

        Well, WP won’t do it until the numbers justify it.

        Clearly, but don’t you remember the BrowseHappy campaign that Automattic took over? Clearly they and/or the community at large can advocate for sooner change if they really want to.

        We should focus our efforts on hosts and users to switch…

        So what efforts are we taking? ;-)

          Using your approach you’d have to use a global variable, right?

          Yeah, I haven’t come up with a way of encapsulating data like that that is both elegant and detached from the global state. I suppose I would either use the object cache or a similar methodology to the one I detailed above.

          The problem with using the object cache is that, while it’s fairly straightforward and “elegant”, in a production environment it creates a persistent global state, which is even worse than just using a global variable.

          The problem with my little song and dance method is that it is not accessible to accidental programmers, and is probably overly complex, and may even be very difficult to debug (although I have not found this to be the case).

          Clearly they and/or the community at large can advocate for sooner change if they really want to.

          True, but that’s not what you said. ;)

          It would indeed be great if the whole WP community (but especially the core team and Automattic) started pushing hosts to upgrade to 5.4 now. I know DreamHost already is doing so.

          So what efforts are we taking?

          I am writing and sharing helpful functionality with 5.3 as a requirement. If people want to use it, they either have to meet that requirement, or understand the language well enough to translate it. I don’t share my code with or for accidental programmers; if they want to graduate to purposeful programmers, they’re going to have to learn this stuff eventually anyway. If they don’t, well, there are already more than enough tutorials on how to write >PHP5.3.

            Yeah, I haven’t come up with a way of encapsulating data like that that is both elegant and detached from the global state.

            Seems to my that by avoiding classes you are avoiding the thing specifically designed for that! :) But then maybe your coding style rather needs encapsulating data though mine usually does.

            True, but that’s not what you said.

            Yeah, but that’s what I meant! Can’t you read between the lines? ;-p

            I don’t share my code with or for accidental programmers; if they want to graduate to purposeful programmers, they’re going to have to learn this stuff eventually anyway.

            In my experience most accidental programmers are only programmers grudgingly; most would prefer not to have to program at all. For them being a “purposeful” programmer is not in the cards.

            Good adjective, BTW; I’ll be stealing it for future use. :)

              Seems to my that by avoiding classes you are avoiding the thing specifically designed for that! :) But then maybe your coding style rather needs encapsulating data though mine usually does.

              I don’t know; It’s so seldom that I even need to have encapsulated data. Take the example you used above; the only use case I have for the hook suffix variable returned by add_*_page functions is to add an action on the "load-$hook_suffix" hook. But why spend the extra memory to add a hook to both admin_menu and admin_init hooks and store that variable in an external (and persistent) value when I could just grab it as a local variable inside my admin_menu callback and add the action directly to “load-$hook_suffix” from inside that callback? The things I actually do with WordPress generally end up revealing to me that I’m being too “clever” with my code when I rely on classes as a namespace or module organization tool rather than an object template.

              Yeah, but that’s what I meant! Can’t you read between the lines? ;-p

              I can only read the words as you press them. ;)

                he only use case I have for the hook suffix variable returned by add_*_page functions is to add an action on the “load-$hook_suffix” hook.

                I can envision another; remove_action(). If you don’t capture it you disalllow someone else from (easily) disabling/chaining the code that adds your menu. Isn’t that a concern?

                But why spend the extra memory to add a hook to both admin_menu and admin_init hooks and store that variable in an external (and persistent) value when I could just grab it as a local variable inside my admin_menu callback and add the action directly to “load-$hook_suffix” from inside that callback?

                Is that level of memory use really a legitimate concern? You’d be using ((my guess)) somewhere between 1/1000th and 1/10,0000th additional memory when compared with just any WordPress page load. If that memory is really a concern doesn’t it point to WordPress as being the wrong solution for your use-case?

                I can envision another; remove_action(). If you don’t capture it you disalllow someone else from (easily) disabling/chaining the code that adds your menu. Isn’t that a concern?

                Generally, I put validation/sanitization/auth checks on those hooks (load-$hook_name). If someone is removing that hook and not the menu hook, they’re definitely doing it very wrong. There’s plenty of time before admin_menu to remove my plugin’s menu hook, something even easier for accidental programmers using namespaced functions than doing the same thing with a singleton. As for adding to that code, I can always add custom hooks to the load function itself, or even in the admin_menu callback.

                If somebody really needs to remove that action or use the hook suffix, they can always use get_plugin_page_hookname( 'submenu-slug', 'parent-slug' );. Is that such a terrible fate?

                Is that level of memory use really a legitimate concern? You’d be using ((my guess)) somewhere between 1/1000th and 1/10,0000th additional memory when compared with just any WordPress page load.

                Yes. Irresponsible and sloppy memory usage is always a concern, especially as WordPress scales. You know that. WordPress won’t ever be taken seriously in engineering circles while that attitude exists. We can do better.

                If that memory is really a concern doesn’t it point to WordPress as being the wrong solution for your use-case?

                No. The implication of your question is that writing finely tuned and well optimized code is not worth doing and should be avoided by picking a solution based on how little optimization I can get away with rather than based on the needs of the client and project. I doubt that’s what you meant, but I find it laughable that the idea that my desire to write good solid optimized code is a sign that WordPress isn’t the right platform to build on.

                I know how much you want WordPress to succeed in the business and enterprise sector, but as long as we talk about optimization like it’s something you do after your site crashes I just don’t see that happening.

                Hi @John,

                If somebody really needs to remove that action or use the hook suffix, they can always use get_plugin_page_hookname( ‘submenu-slug’, ‘parent-slug’ );. Is that such a terrible fate?

                Fair point. Although it places a higher burden of knowledge on the site builder who uses your plugin if you proactively document who to remove your hooks then I guess this one use-case is addressed.

                Yes. Irresponsible and sloppy memory usage is always a concern, especially as WordPress scales. You know that.

                I assert strongly that advocating the instantiation of one PHP class with a handful of properties is not “irresponsible” nor “using memory sloppily” and am a bit annoyed you would imply I’m proposing being irresponsible and sloppy. You are conflating a proverbial mountain with a mole hill.

                WordPress won’t ever be taken seriously in engineering circles while that attitude exists.

                Do you really believe that those “engineering circles” you quote will “ever” take WordPress seriously? They can’t even get past the use of PHP let along lack of MVC; I doubt they ever approve of WordPress no matter how few classes you instantiate.

                I also don’t think it matters one iota what self-defined “engineers” think because both the PHP language and the WordPress platform works, works well and keeps getting adopted no matter what they think.

                And as an aside, I’m always a bit rankled when I hear people whom no institution has granted the title of “engineer” chose to co-op the term and use it to refer to themselves. I know how to prescribe an aspirin but I don’t call myself a doctor. Truth be told maybe it just annoys me because I spent well over four difficult years to be granted a college degree in engineering. But I digress…

                No. The implication of your question is that writing finely tuned and well optimized code is not worth doing and should be avoided by picking a solution based on how little optimization I can get away with rather than based on the needs of the client and project.

                No, the implication of my question is that avoiding minute levels of memory use is a premature optimization and your reply presumes that memory and performance are the only aspects for which to optimize and that is clearly not the case. Other aspects include maintainability, robustness, flexibility, security, ease of implementation and so forth. It’s clear your focus is on the former whereas mine in on many of the latter. Your focus doesn’t make you “wrong” (unless you ignore all other aspects.) Conversely I’d appreciate if you wouldn’t imply that my focus makes me wrong.

                I doubt that’s what you meant, but I find it laughable that the idea that my desire to write good solid optimized code is a sign that WordPress isn’t the right platform to build on.

                What I meant was if your only concern is memory use and performance then you definitely are on the wrong platform. If you balance those concerns with maintainability, robustness, flexibility, security, ease of implementation then my comment probably does not apply.

                I know how much you want WordPress to succeed in the business and enterprise sector, but as long as we talk about optimization like it’s something you do after your site crashes I just don’t see that happening.

                Again, there is a lot more to optimize for than just memory and performance; not every use-case needs those even. I’ll bet that maintainability, robustness, flexibility, security, ease of implementation are far more important to the 80% of WordPress sites than current memory use and current performance.

                I’m NOT saying performance and memory use are not important – they are – I’m saying they are not the only thing that is important. “All things in moderation” is a good rule of thumb to live by.

                Again I’m not saying your focus is wrong; we need performance-obsessed people as much as we need people obsessed with other concerns. Just please don’t imply I’m irresponsible or sloppy because my obsession is not inline with yours. We all can’t optimize for everything, by definition. :)

                P.S. Just to satisfy my own curiosity I took my local test website running 3.5.1, disabled all plugins and selected the Twenty Twelve theme. I placed an echo for the output of memory_get_usage() at the beginning of index.php and then one at the bottom of the theme’s functions.php file; here’s the Gist for the latter code. What I found was that loading WordPress thru functions.php takes 20.3Mb. One class instantiated with a handful of properties takes 0.00031Mb meaning WordPress itself takes 3248 times the use of my example class with a few properties (please take these measurements as just approximates as different test cases should differ.)

                I got more curious and decided to benchmark the memory used by create_initial_post_types(). It used 0.12Mb, or 19.85 times as much memory as my example class. You can review my calculations at this Gist.

                Based on this and my prior experience I assert that focusing as a primary concern on the memory use of a construct that takes 1/3,248th of what WordPress takes without regard to maintainability, robustness, flexibility, security, ease of implementation and so forth is premature optimization. I further assert that any serious implementation of WordPress at “enterprise” scale will rarely be using that memory because most of the pages will be served from static files by Nginx or similar reverse proxy caching system.

                To me programmer productivity is just as important if not more important to optimize for than memory use or execution cycles. But again that’s just what I value, YMMV. FWIW.

                P.P.S. For anyone else reading this, I have a lot of respect for John and I believe he feels the same. We are just enjoying a dogmatic debate where we both do our best to make our cases. :)

                Just so this is the first thing you read after Mike’s P.P.S, Mike and I do indeed have immense mutual respect for each other and we are indeed enjoying a friendly discussion.

                I assert strongly that advocating the instantiation of one PHP class with a handful of properties is not “irresponsible” nor “using memory sloppily” and am a bit annoyed you would imply I’m proposing being irresponsible and sloppy.

                Sorry for not being more explicit; I do not think you are sloppy and irresponsible with your coding practices. But other people are. A bunch of classes with a handful of properties may not be anything to worry about, but people get into bad habits far more easily than out of them.

                You are conflating a proverbial mountain with a mole hill.

                Just like one wouldn’t say “don’t worry about that security stuff, you can always figure it out later”, I don’t think we should be communicating “don’t worry about writing efficient code; we can figure that part out later.”

                Do you really believe that those “engineering circles” you quote will “ever” take WordPress seriously?

                Let me restate what I was trying to get at. I’m not saying my approach is the key to getting WordPress used everywhere; I’m saying that dismissing concerns of performance and optimization are blockers. Removing that roadblock may not clear the road, but as long as it’s there we’re definitely not moving forward.

                And as an aside, I’m always a bit rankled when I hear people whom no institution has granted the title of “engineer” chose to co-op the term and use it to refer to themselves. I know how to prescribe an aspirin but I don’t call myself a doctor. Truth be told maybe it just annoys me because I spent well over four difficult years to be granted a college degree in engineering. But I digress…

                At the risk of going down a rabbit hole, your own definition of an engineer (I’m making an assumption that your link to Wikipedia was meant to fill that role) states that an engineer is a practitioner of engineering. Sounds like it doesn’t matter whether some institution has sold an overpriced piece of paper to somebody with that word on it. I feel sure that you and I agree that the skill with which any person is able to bring their knowledge of computer sciences to bear in solving technical problems will determine the degree to which they are an engineer. Getting an engineering degree affords one the opportunity to gain much knowledge in the field, but I contend that it does not make one an engineer. There’s plenty of BS out there, both with and without engineering degrees.

                the implication of my question is that avoiding minute levels of memory use is a premature optimization

                My experience has is that this is not the case. If this sort of approach is not taken at the beginning, it is unlikely to ever be done because of the significant amount of refactoring necessary to do so. This is not something that I’m doing prematurely because it’s something that never gets done after the fact.

                Other aspects include maintainability, robustness, flexibility, security, ease of implementation and so forth.

                Well of course those are all important concerns. But most of them have been completely irrelevant to this particular branch of the discussion.

                By the way, if flexibility is a concern I would definitely rethink using singletons.

                I’m NOT saying performance and memory use are not important – they are – I’m saying they are not the only thing that is important. “All things in moderation” is a good rule of thumb to live by.

                Would you recommend security in moderation? Some things don’t fall under that rule of thumb and I think performance and memory use are in such a category.

                Those are some very interesting test results. I had no illusions that your approach would be any kind of memory hog (at least, not in isolation). However, I don’t see what WordPress’ internal code has to do with our discussion. I thought we were talking about 3rd party code, not core.

                Of course something like create_initial_post_types is going to have a bigger memory footprint than instantiating a basic class. It’s doing way more! I think it’s apples to oranges to compare your class’ footprint to WordPress’ use of memory. Unless your class is creating post types for posts, pages, nav menus, attachments, and revisions in its constructor. If that’s the case, you should probably submit that code to core as a patch. ;)

                I further assert that any serious implementation of WordPress at “enterprise” scale will rarely be using that memory because most of the pages will be served from static files by Nginx or similar reverse proxy caching system.

                I counter that, from my own experience implementing WordPress sites at “enterprise” scale, that’s not a good enough answer. For one thing, no site is 100% cached all the time. For another thing, the admin is never cached. And that’s where all of these concerns are most important. If a visitor to a site gets a slow experience, they don’t think “WordPress is slow!”, they think the site is. If somebody using the admin area of WordPress has a slow experience, you know they’re going to blame WordPress.

                To me programmer productivity is just as important if not more important to optimize for than memory use or execution cycles.

                On that note, I should get to work… :)

                A bunch of classes with a handful of properties may not be anything to worry about, but people get into bad habits far more easily than out of them.

                I struggle with the belief we should dumb down everything just because some people misuse things. We can’t protect everyone from their own ignorance.

                Just like one wouldn’t say “don’t worry about that security stuff, you can always figure it out later”, I don’t think we should be communicating “don’t worry about writing efficient code; we can figure that part out later.”

                I think our disagreement is on what constitutes “inefficient coding.” I’d say in the spectrum you are more on an extremist than me. :)

                Let me restate what I was trying to get at. I’m not saying my approach is the key to getting WordPress used everywhere; I’m saying that dismissing concerns of performance and optimization are blockers. Removing that roadblock may not clear the road, but as long as it’s there we’re definitely not moving forward.

                And let me say my point a different way; worrying about performance and optimization above everything else is to me like throwing out the bathwater prior to washing the baby for fear the water might not be clean. :)

                At the risk of going down a rabbit hole…

                Call me old-fashioned in this case, but I think the rigor required of 4+ years of college and confirmation by those who have previously proven themselves (a.k.a. “professors”) is more validating than being self-taught. I guess I just think honorary titles should be earned, not co-opted.

                I’m a degreed mechanical engineer but I’m a (mostly) self-taught programmer. I think I’m a highly skilled practicioner of programming but I wouldn’t call myself a “software engineer.” Even the IEEE that offers two software engineer certifications doesn’t use the word “engineer” because in some parts of the US the use of the term Engineer is regulated only to those who have a Professional Engineer license which frankly means I’m not an engineer either even though I have the degree.

                Interestingly though, as of this month the NCEES has a Principles and Practice of Engineering Examination Software Engineering Exam Specifications.” But it just came out this month so all the prior use doesn’t cut it with me. So, pass that test and I guess I’ll be happy to call someone a “software engineer.” Don’t take the test? Not so much. Just sayin…

                Well of course those are all important concerns. But most of them have been completely irrelevant to this particular branch of the discussion.

                Actually, not exactly. I’ve been thinking of code I’ve written for others to reuse, and that’s part of the reason I belabor this issue.

                By the way, if flexibility is a concern I would definitely rethink using singletons.

                Your making that comment tells me you either have not read my comments and posts about the use-cases for singletons or you scanned them assuming you already knew the subject. My use of singletons is to wire hooks, and given that use-case all the flexibility concerns I’ve read thus far about singletons do not apply.

                That immediate dismissal of an approach without first making sure to understand the use-case has recently become one of my pet peeves (since I starting blogging about Singletons and WordPress plugins, that is. :)

                I don’t see what WordPress’ internal code has to do with our discussion. I thought we were talking about 3rd party code, not core. … I think it’s apples to oranges to compare your class’ footprint to WordPress’ use of memory.

                The point is one of magnitude. By analogy when you are evaluating the purchase of an SUV you wouldn’t worry about an extra 10 pounds between options but you would worry about 10 pounds difference when buying a bicycle unless you are a masochist!

                So if you are going to use WordPress for your project then its memory footprint is directly relevant to the memory usage of your own plugins. It makes great prose to say a butterfly flapping its wings around the world can create a tidal wave but nobody in their right mind are worried about a rabble of butterflies in Indonesia when in the US making plans for the weekend.

                If you can’t use a single class instance with a few properties because of the memory it occupies then WordPress is very much the wrong basis for your project, just as bad as adding 10 pounds to your bike. But if WordPress is the right basis for your project then a single class instance with a few properties is trivial in comparison to the memory footprint of WordPress just as the extra 10 pounds on your SUV won’t mean naught.

                Unless your class is creating post types for posts, pages, nav menus, attachments, and revisions in its constructor. If that’s the case, you should probably submit that code to core as a patch.

                Why bother? It’s hard enough to get them to add a single hook let alone an entire new subsystem. But I digress…

                For another thing, the admin is never cached. And that’s where all of these concerns are most important. If a visitor to a site gets a slow experience, they don’t think “WordPress is slow!”, they think the site is. If somebody using the admin area of WordPress has a slow experience, you know they’re going to blame WordPress.

                I completely agree with that, I felt the same about Drupal because of the horrid admin performance.

                However, I think your “Don’t use singleton classes for plugins because of the memory overhead” argument completely trivializes the potential techniques used for loading plugins.

                For example, one of my libraries (which I can tell by your comments you would hate) is architected for progressive instantiation of classes and arrays for only those URLs that actually need them, or at least the best that can be done without overwhelming complexity. But it needs properties to make judgements about what to instantiate at runtime.

                Using the approach you advocate I would not be able to make these kind of judgements and also have most of the functionality for a plugin already developed when I start a project. I’ll happily spend a tiny bit of memory for that.

                On that note, I should get to work…

                <sigh> :) Me too.

          Actually, now that you mention BrowseHappy, that’s an interesting idea for how to advocate 5.3 upgrades. Given upgrading your browser is a whole different issue than upgrading PHP, but I guarantee that the large majority of admins using PHP 5.2 are on hosts that actually do support 5.3 (and have for a long time). It’s usually the customer’s choice and they never force users to upgrade until that PHP version is actually being removed from the system entirely. In many cases, it’s just a simple radio-button selection in their hosting control panel.

          As long as it’s not terribly intrusive, and can be easily dismissed, I kind of like that approach for advocating upgrades.

            @Bryan – You work for a web host right? Any chance you could write up a “how to” and get WP Daily to publish, to kickstart things?

              I second Mike’s suggestion to draft a post for WP Daily – it’d be an awesome post, welcome contribution, and definitely useful to a lot of the readership.

              At any rate, thanks for the comment – interesting stuff.

    I’d say that WordPress itself is an anti-pattern so it’s hard to speak of patterns or coding standards with it at all. Actually It’s hard to speak with coding standards these days at all. Python is a standard, PHP not.

    Nonetheless singleton limitations can be obvercome with interfaces.(That’s probably explained in the links I posted)

    I usually use static classes or singleton instances as it makes the code clean and much easier to read, OOP and patterns aside – this is WP

    As for the gist given, while it’s tricky it’s nearly the same as global variable. (although more resource prone). Moreover it’s probably against the idea of filters,as they are used to give the facility of changing otherwise hardcoded values, don’t you think?

      @Rafal: “I’d say that WordPress itself is an anti-pattern”

      I like that, assuming you mean it positively; i.e. it’s an anti-pattern in the academic sense but used as a whole it works well I had this conversation after the PHP group last night with someone using Symfony 2; we agreed best practices for Symfony 2 != best practices for WordPress.

      Mind if I use that phrase in the future? :)

        Actually I consider WordPress a set of worst CODING practices haha – it was a purely negative statement. WP is a great example of illogical naming, abuse of global variables and design flaws as well ;)

        It makes me a hypocrite however, since I do consider WP an amazingly successful platform, especially knowing that it’s started around 10 years ago. Moreover I earn for a living thanks to it ;)

          @Rafal – I’ve spent a lot of time contemplating WordPress’ “bad” coding practices juxtaposed with the success the WordPress ecosystem has had with extending WordPress and compared with the two other developer ecosystems that I spent at least 12 and 7 years working in respectively; Visual Basic and Clipper. My current conclusion is that the convention/academic wisdom about what is “good” and what is “bad” is flawed.

          More specifically I’ve come to believe there are not absolutes when it comes to coding patterns, i.e. one pattern is not good 100% of the time and another pattern bad 100% of the time; it all depends on context and target coder; i.e. what’s good for a professional C++ programmer is not the same as what’s good for a designer/accidental programmer.

          I could and probably will write several long posts on this topic so I won’t belabor the point here but suffice it to say when I hear a black-and-white declaration of an approach to coding being “bad” I no longer take that assessment at face value.

          Ouch I can’t reply to your post :(

          Well I mostly agree with your reasoning and I do not consider myself as a warden of academic rules. I mentioned python (and I was thinking about Django) becuse it doesn’t allow you to code stuff differently which makes every project easier to understand.

          If each one of us uses different approach and coding standard per project then there’s no standard at all. And this will continue forever ^_^

          WP is a success just like Microsoft Kinect is, but it doesn’t mean that they are good pieces of software or hardware at all. They are just usable and have gained popularity among the people.

          Basically with web projects there’s only one strict standard, that is HTML :)

          @Rafal – Note that I wasn’t intending to cast any aspersions on you or anyone who asserts the convention wisdom, I’m just thinking we need to start questioning convention wisdom instead of assuming that patterns are “one-size-fits-all”.

          If each one of us uses different approach and coding standard per project then there’s no standard at all.

          Oh, I’m a HUGE believer in standards per project; the reason I started the HardcoreWP blog at the end of last year was I wanted to encourage the use of standards and have a say in trying to establish the ones that people in the WordPress community use.

          Instead I’m asserting that coding standards for WordPress are necessarily different then they are for Symfony, for example. And I’m also asserting that that is not a bad thing.

          but it doesn’t mean that they are good pieces of software or hardware at all. They are just usable and have gained popularity among the people.

          Note that I did not say that the WordPress way of coding is good because WordPress has lots of users, I (effectively) said there is strong evidence to believe that WordPress is good because of the success in the way WordPress has been able to be extended, i.e. the success of the WordPress ecosystem.

          I “came of age” in programming back when the conventional wisdom was that the idea of “reusable modules” was a panacea that we’d never achieve. And instead we have definitely achieved it . In the mid 90’s Visual Basic had a thriving 3rd party component market (I know, I ran a catalog mail order business that sold those components) and we’ve seen reusable modules achieved in so many other places too, but few other platforms as strongly as with WordPress.

          So what I’m asserting is that the coding patterns in WordPress lend themselves to this amazing level of plug-and-play interoperability from so many different developers which leads me to ask “If it’s this successful at achieving interoperability, how can the coding styles that so many people hate on really be that bad?”

          Basically I just ask you this: contemplate for a while this concept that maybe some of the “bad” approaches WordPress uses, i.e. global variables, globally visible hooks, really long functions, etc. are not only not bad but in the context of WordPress development may actually have been and continue to be one of the reasons the WordPress coding ecosystem works so well.

          @Mike Thanks for the encouragement ;)

          Actually I was about to write that:

          @Mike – one last thing ;)

          Your argument about how WordPress has been extended is insubvertible :)

          Personally I never take black or white assumptions about anything, people who think like that will probably never evolve…

          You’re absolutelly right, WordPress has probably become that enormous thanks to its accessibility. And yet I agree, that from the mentioned point of view these coding standards are good or even perfect.

          I was just trying to be an advocate of the quality coding (which is most probably unachievable to the plenty of plugin developers) – and if forced would make WP an elite software :-) I’m mostly concerned about the safety and memory consumption. Occurences of services like http://vip.wordpress.com/ make me contemplate about the negatives.

          You’re doing the same (being an advocate of good practices) I see:

          Oh, I’m a HUGE believer in standards per project; the reason I started the HardcoreWP blog at the end of last year was I wanted to encourage the use of standards and have a say in trying to establish the ones that people in the WordPress community use.

          I’ll be checking your blog with pleasure :)

          Accessibility itself is a problem, that I face. Should the application be faster, more secure and safe or should we make it accessible?


          Basically I just ask you this: contemplate for a while this concept that maybe some of the “bad” approaches WordPress uses, i.e. global variables, globally visible hooks, really long functions, etc. are not only not bad but in the context of WordPress development may actually have been and continue to be one of the reasons the WordPress coding ecosystem works so well.

          Agreed :)

          Oh and last thing is that my frustration comes from today’s work I had with a plugin that was supposed to be fabulous which happened to be nonfunctional locally (it’s author said it wasn’t even tested locally (sic!))

          @Rafal – I think we are converging on agreement. :)

          And I really like your use of the term “accessibility”; I hadn’t thought to use it here but I think it really applies. Consider the two following approaches; which this code might be _”better”_ for a PHP-based MVC system (yes, my example is simplified):


          $cpt = WP::post_type::build( 'my_cpt' );
          $tax = WP::taxonomy::build( 'my_tax' );
          $cpt->attach_taxomomy( $tax );
          WP::register( $cpt );

          I really think this code is more accessible in the WordPress world:


          register_taxonomy( 'my_tax' );
          register_post_type( 'my_cpt', array(
          'taxonomies' => array( 'my_tax' )
          ));

          My friend @Taras above and I have a name for the latter approach, we call it “WordPress-ish.” :)

          P.S. I concur and share in your frustration over the (lack of) emphasis placed on best practices in plugin development in the official repo. We could share many stories… Oh, and you extended my vocabulary today; I had to google the definition of “insubvertible” :)

          @Rafal – I think we are converging on agreement.

          Yes, indeed :)

          Obviously the latter is much better (or accessible as they say ;))
          “WordPress-ish.” – nice term, noted down.

          I concur and share in your frustration over the (lack of) emphasis placed on best practices in plugin development in the official repo. We could share many stories…

          Code sniffers are quite good lately I wish they were bundled (and very accessible to the community)
          This one’s being extended by my fellow X-Team members: https://github.com/mrchrisadams/WordPress-Coding-Standards (Chris Olbekson and Weston Ruter)

          Oh, and you extended my vocabulary today; I had to google the definition of “insubvertible”

          Considering the fact that English is not my mother tongue I take it as a huge compliment :))

        As for the phrase go ahead and use it (in a positive way) I understand your reasoning as well ;) Just tell to the people when was it first mentioned please ;)

        This one’s being extended by my fellow X-Team members: https://github.com/mrchrisadams/WordPress-Coding-Standards (Chris Olbekson and Weston Ruter)

        Very interesting, and thanks for sharing. What’s the status of this, just starting? I can’t tell for sure but it seems like it’s showing an example of how someone might build a standard ruleset and not a ruleset itself.

        This could be a fantastic community project if it got enough of the right people’s attention.

        On another pedantic note, it’s too bad that PHP_CodeSniffer doesn’t support JSON in addition to XML. I always grimace at the thought of having to work with XML, but I digress…

          Very interesting, and thanks for sharing. What’s the status of this, just starting? I can’t tell for sure but it seems like it’s showing an example of how someone might build a standard ruleset and not a ruleset itself.

          Nah, it’s few months old already. Weston’s in charge, so please contact him directly to get more clues on that project.

          On another pedantic note, it’s too bad that PHP_CodeSniffer doesn’t support JSON in addition to XML. I always grimace at the thought of having to work with XML, but I digress…

          Perhaps it’s high time to gather the community and sort it out? ;)

          Anyway it’s quite late here in Poland. I need to leave. Thank you for an interesting exchange of opinions, I’m glad we came to the conclusion :))

          Take care

      WordPress may be, but my code doesn’t have to be.

      I’m very familiar with Eric’s posts. He and I are currently working on a few projects together and I value his insight and brilliant thought immensely. I’ve definitely used his ideas regarding singletons to great effect. Since you had already mentioned that particular take on Toms question, I decided it didn’t need to be mentioned. :)

      Nobody’s going to force you to use any code you don’t want to.

      I’d say that WordPress itself is an anti-pattern so it’s hard to speak of patterns or coding standards with it at all.

      Ha! I know that lots of developers hate on WordPress core – and don’t get me wrong, there is bad code in there – and compared to other frameworks or foundations, we’ve a long way to go.

      But the two things I have remember is this:

      WordPress didn’t start out aiming to be a framework like, say, Rails, Yii, or Symfony. I’m not saying that this exempts it from good development practices – certainly not – but that it’s unfair for us to expect it to cater to a more developer-friendly environment when that has been added over time.
      Just because the foundation is weaker on good development practices doesn’t mean that we can’t do the best that we can on top of what we have, you know? The way I see it, as a programmer who tries to write the best code that he can, I can only do so much about the foundation, but I can do a heck of a lot more with my own code.

      Moreover it’s probably against the idea of filters,as they are used to give the facility of changing otherwise hardcoded values, don’t you think?

      Now this brings up an interesting point. Gonna think about this one for a bit :).

    I’d use the singleton (anti-)pattern, as Rafal mentioned above.

    I’m intrigued as to why you refer to why you mention it as an anti-pattern? Don’t read me wrong – I think it can be misapplied, and there are certainly alternatives that can be used in place of it – but I do think, as far as design patterns go, it has its place.

    For any project I can manage it, I make PHP 5.3 a requirement and end up using namespaces and better function names; classes are only for real objects and everything else goes in a function (the exception being classes that have to extend WordPress’ own classes).

    To some degree, you and I are one and the same here. When I have more control in client projects, I try to make sure we’re able to use the most recent version of PHP if for nothing else than to take advantage of newer features.

    That said, I’ve rarely used namespaces in WordPress development (though I used them like whoa back when I was doing .NET).

    I like the idea, though and it’s something I need may to get back into practicing. Honestly, I’m in the practice of breaking things out into classes, but I’ve yet to really worry about namespacing because I haven’t had to need – at least not yet.

    I’m more of a pragmatist that will basically wait until I have compelling reason to do something before actually doing it (not saying you aren’t, just sharing my own approach).

      I’m intrigued as to why you refer to why you mention it as an anti-pattern?

      Because it causes more problems than it solves and there are clearly documented better alternatives (assuming 5.3 is a minimum requirement). That’s the definition of an anti-pattern.

      Yes, it’s less of an anti-pattern in PHP than in other languages, and even less of one in WordPress; I see those as quantitative differences rather than qualitative.

      I’m more of a pragmatist that will basically wait until I have compelling reason to do something before actually doing it

      Switching to namespaces means logical organization of code into discreet functions, no memory footprint from instantiating classes that have no right to exist and everything is 100% straightforward to unit test because none of it relies explicitly on global state. That was a compelling enough reason for me. :)

        Switching to namespaces means logical organization of code into discreet functions, no memory footprint from instantiating classes that have no right to exist and everything is 100% straightforward to unit test because none of it relies explicitly on global state. That was a compelling enough reason for me. :)

        Ack! Touche for this :).

        Now I’ve gotta experiment with it a bit.

        I’ve noticed a lot of non-WordPress programmers immediately begin thrashing about with a cross, a garlic bulb necklace and some holy water when they hear the word “singleton” instead of first understanding the use-case. The use-case where I’ve found singletons to be appropriate is to hook actions and filters on a page load; the same thing you use namespaces and functions for. In that case, at least IMO, singletons are not an anti-pattern.

I know nacin recommends using a static variable in the class — something like

http://www.slideshare.net/andrewnacin/best-practices-in-plugin-development-wordcamp-seattle (go to slide 8)

My contribution to the question of “How to instantiate a WordPress plugin?” has been the planned subject of my next blog post, sitting in draft mode for over a month! Darn clients, they keep getting in the way of the fun stuff! :)

My suggestion is to use a instantiate() method of a singleton class in the 'plugins_loaded' hook. This is the follow-up to the post that @Taras mentioned above and thanks to Frank Bueltge’s insistence that using a hook is a better way:

add_action( 'plugins_loaded', array( 'My_Plugin_Class', 'instantiate' ), 9 );

Note I’m using priority 9 so that the plugin will be fully loaded before any 'plugins_loaded' hooks that at the default priority of 10 fire in case they are dealing with the available and loaded plugins. This also allows another plugin to hook 'plugins_loaded' at 8 or earlier to disable the plugin class instantiation, if need be.

    Note I’m using priority 9 so that the plugin will be fully loaded before any ‘plugins_loaded’ hooks that at the default priority of 10 fire in case they are dealing with the available and loaded plugins. This also allows another plugin to hook ‘plugins_loaded’ at 8 or earlier to disable the plugin class instantiation, if need be.

    Really appreciate this breakdown especially because when developers begin mucking with the priority of things happening and not describing it, it leaves the rest of us to guess which is fine … if we guess right.

    Otherwise, too many others end up following suit not knowing why we’re (or they’re) doing what they’re doing.

I write all of my plugins in a singleton fashion now with a helper function that returns the instance, based on a format similar to how bbPress does it. So if my plugin is called “Viper’s Cool Plugin”, you could do VipersCoolPlugin()->some_class_method().

Some examples of this style:

https://github.com/Automattic/P2-Resolved-Posts/blob/master/p2-resolved-posts.php
http://bbpress.trac.wordpress.org/browser/trunk/bbpress.php
https://github.com/SupportFlow/supportflow/blob/master/supportflow.php
https://github.com/Automattic/Edit-Flow/blob/master/edit_flow.php

I’d say that WordPress itself is an anti-pattern so it’s hard to speak of patterns or coding standards with it at all.

Yes, quite likely WordPress itself is an “anti-pattern”… Why? Because many of the perfectly legit OOP patterns become anti-patterns in when used WordPress code! For example, Dependency Injection is an overkill in more cases than not. I cannot remember the last time I saw Memento or Flyweight in WP codebase…

I’d say that one of the reasons for that, is that WordPress is an extendable web app and not a framework. The other reason is the “share-nothing” architecture of PHP.

Many of the perfectly legit OOP patterns become anti-patterns, when used in PHP/WordPress code. If you are re-reading GOF book to put up your plugin together, well … you are _doing_it_wrong()!

One of the main reasons of why WP gained popularity, is that in many cases all you needed to do as a “webmaster” was “just paste these lines in your functions.php”… Therefore, do not expect “Thank you” letters from those who have to debug/test/extend or otherwise build upon your smart*ss code.

Your overly OOP-ish code does not mean you are an accomplished WP developer. Quite the opposite — it is one of the signs you have not mastered “the WordPress way” yet…

(Nothing personal, just a general note.)

The biggest thing I hate about using create_function() to register is a widget is that there is no easy way for another developer to remove your widget. Normally, they might use remove_action() to rid of your callback, but not they need to register another callback and unregister the widget right after it was registered.

As for initializing classes, I’m a fan of using a class with just static methods, no constructor, and then the class just acts as a namespace wrapper, and I can start it like so:

add_action( 'init', array( 'My_Plugin_Class', 'init' ) );

I do things like this for all plugins that don’t really need class methods to be accessible outside the class.

I must say: this is an incredibly interesting discussion. I personally prefer an approach where I use static class methods, as they are easily unhookable and do allow for proper functionality separation without using the global namespace.

However, my opinion on this matter turned out to be way too extensive for a comment, so I decided to write an article about it (http://bit.ly/YZ77sK).

I think namespaces will be the most common method in the future, just as soon as PHP 5.3 or up has really become the standard.

Leave a Reply

Name and email address are required. Your email address will not be published.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>