2
\$\begingroup\$

I am developing a library to easily register WordPress custom post types and taxonomies.

But the problem is I can't use one instance of object because of adding the object in WordPress hooks.

So what I have done as a solution is to re instantiate the class every time when you want to register a custom post type. Is that okay according to the modern PHP development?

 /**
     * @return PostType
     */
    public static function getInstance(){
        // don't need singleton due to wordpress hooks :( sadly i need to learn wp more.
        return new PostType();
    }


    /**
     *
     */
    public function register(){
        // Hook into the 'init' action
        add_action( 'init', array($this,'hookInWordPress'), rand() );
    }

    /**
     * callback of hook in init action
     */
    public function hookInWordPress(){
        $this->toSlug();
        if($this->newTaxonomy){
            $tax = $this->newTaxonomy->register($this);

            $this->addTaxonomy($tax->slug);
        }
        $args = $this->buildArgs();
        $args['labels'] = $this->buildLabels();
        if($this->icon) {
            $args['menu_icon'] = $this->icon;
        }

        register_post_type( $this->slug, $args);
        flush_rewrite_rules();
    }

Full project on GitHub

\$\endgroup\$
1
\$\begingroup\$

Of course it's ok. You will have 1 object per post type. GetInstance is called factory method.

I have noticed two strange things in your code:

  1. PostType.php Line 116

Why do you use random here? It will be ok if you leave default priority param.

  1. PostType.php Line 123

    You call toSlug function before slug usage but it's better to call it when name was setted up here PostType.php Line 380

This way you will never forgot to call toSlug before slug usage.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.