Custom plugin: Class designΒΆ

  • MyContent (some codes have been removed for brevity)
<?php
        class MyContent {
                static $all_langs = ['en' => 'English', 'nl' => 'Nederlands'];

                static function get_fields() {
                }

                function get_result() {

                }
        }

?>

The most important methods are get_fields, which provides fields for post type in the admin section and frontend, and get_result, which get the the field saved on backend. (more detail at mycustom/klass.php)

  • BaseRepository
<?php
        class BaseRepository {
                private $wp_query;
                private $config;
                private $klass;

                function __construct($config, $klass) {
                        $this->config = $config;
                        $this->klass = $klass;
                }

                function setWpQuery($obj) {
                        $this->wp_query = $obj;
                }

                function findAllByCondition($array_condition) {
                        $this->wp_query = new WP_Query(array_merge($this->config, $array_condition));
                        $res = [];
                        $objs = $this->wp_query->posts;
                        foreach($objs as $obj) {
                                $item = new $this->klass($obj->ID);
                                $res[] = $item->get_result();
                        }
                        return $res;
                }

                function findFirst() {
                        $res = $this->findAllByCondition(array());
                        if(sizeof($res) > 0) {
                                return $res[0];
                        }
                        return false;
                }

                function findAll() {
                        return $this->findAllByCondition(array());
                }

                function findAllByOrderByIntegerKey($keyname) {
                        $res = $this->findAll();
                        usort($res, function($a, $b) use($keyname) {
                                return intval($a->$keyname) < intval($b->$keyname);
                        });
                        return $res;
                }
        }

This class is intended to be a base class (hence the name!) for all Custom post type Repository. It provide some important method: findAll, findFirst, (more detail mycustom/klass.php)