WordPress Object Oriented plugin development [closed]

A few things stand out.

  • Don’t load all your classes and files up front.

Load admin class when
admin_init hooks fire and front-end classes when front-end hooks fire. Just think about lazy loading as much as possible.

  • If database is an extension of helper then why initialize the base class?

That should be taken care of by database.

  • Why hook 'init' multiple times?

Create an 'init' function and add one hook:

add_action('init', array($this,'my_init');
  • Classes should be CamelCase

Don’t make a class lowercase, ever.

In other languages it’s not ideal to put actions in the initializer for the instance. Consider __invoke() as an alternatives. Unless you think someone might use the initializer later on…

self::$instance = new helper(); // __construct
self::$instance(); // __invoke

http://wppb.me/ does an interesting job of separating out admin loading from front-end loading.

And @toscho had a good link to https://github.com/object-calisthenics/phpcs-calisthenics-rules


Note: This is a rough outline of what I was thinking but I haven’t tested it.

<?php

if ( ! class_exists( 'HelperClasses' ) ) {

    class HelperClasses {

        public static function initialize() {

            add_action( 'init', array ( 'HelperClasses', 'init' ) );
        }

        public static function init() {
            require_once( __DIR__ . '/inc/helper.php' );
            require_once( __DIR__ . '/inc/database.php' );
        }
    }

    add_action( 'plugins_loaded', array ( 'HelperClasses', 'initialize' ) );
}

/inc/helper.php

if ( ! class_exists( 'Helper' ) ) {

    /**
     * Class Helper
     *
     * Loaded via HelperClasses on `init`
     */
    class Helper {

        private static $_instance;

        public static function instance() {

            if ( ! isset( static::$_instance ) ) {
                $singleton = new Helper();
                static::$_instance = $singleton;
                $singleton();
            }

            return static::$_instance;
        }

        public function __invoke() {
            // TODO: Implement __invoke() method.
        }
    }
}

/inc/database.php

if ( ! class_exists( 'Database' ) ) {

    if ( ! class_exists( 'Helper' ) ) {
        wp_die('Helper class required');
    }

    /**
     * Class Database
     *
     * Loaded via HelperClasses on `init`
     */
    class Database extends Helper {

        private static $_instance;

        public static function instance() {

            if ( ! isset( static::$_instance ) ) {
                $singleton = new Database();
                static::$_instance = $singleton;
                $singleton();
            }

            return static::$_instance;
        }

        public function __invoke() {
            // TODO: Implement __invoke() method.
        }
    }
}