1

I'm looking to create a plugin that displays a custom posts label for posts that belong to selected categories. And since I'm new to OOP, I'm struggling to understand whether to use arrays instead of classes and why.

Here is the code for my Label class

class EDM_Product_Label {

    private $title;

    private $color;

    /**
     * This is our constructor
     *
     * @return void
     */
    public function __construct( $title, $color ) {
        $this->title = $title;
        $this->color = $color;
    }

}

And here is the (incomplete) code for my frontend class

class EDM_Product_Labels_Frontend {

    public function display_label() {

        // Selected categories for labels
        $labels = array(
            'sale'       => __( 'Sale', 'nerb' ),
            'whats-new'  => __( 'New In', 'nerb' ),
            'trunkshows' => __( 'Trunkshow', 'nerb')
        );

        // Array to store labels which will be displayed
        $labels_for_product = array();

        // If current product belongs to categories in $labels array, store 
        // that label in the $labels_for_product array

        // Method #1 - Generate new product label object for each label and 
        // store in $labels_for_product array
        foreach ( $labels as $id => $name ) {
            if ( has_term( $id, 'product_cat' ) ) {
                $labels_for_product[$id] = new EDM_Product_Label( $name, 'red');
            }
        }

        // Method #2 - Generate new product label using associative array
        // store in $labels_for_product array
        foreach ( $labels as $id => $name ) {
            if ( has_term( $id, 'product_cat' ) ) {
                $labels_for_product[$id] = array (
                    'name'  => $name,
                    'class' => $id
                 );
            }
        } 

    }
}

The thing I'm confused about is whether to use method #1 or #2? I'm leaning more towards method #2 because I don't see the benefit of creating a $Label class; it seems unnecessary.

So in what circumstances will it be better to create a class instead?

Apologies if this sounds confusing!

  • I don't see point of EDM_Product_Label class. Remember OOP solves particular problems. Do not make everything a class now :) – sandrodz Oct 29 '18 at 22:05

Your Answer

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

Browse other questions tagged or ask your own question.