我如何才能更好地从我的类中初始化方法?

时间:2018-01-10 作者:Jonathan Guerin

我有一个生成一些共享链接的类:

<?php

class Post_Share {
    /**
    * Class to add post-sharing capabilities to each post. It has to be initialized within a post page.
    */

    function __construct( $networks = array(), $post, $style, $display_it ) {
        /**
        * Consturctor for the Post_Share class.
        * @param $networks      What networks we want the post to be shared on.
        * @param $post          The post itself.
        * @param $style         Which style the sharer should have.
        * @see .share-style-2 in style.css to see what available styles we have.
        */
        $this->networks         = $networks;
        $this->post             = $post;
        $this->style            = $style;
        $this->display_it       = $display_it;
    }

    private function generate_social_output() {
        /**
        * Function to build the social share links. The way it works is we keep adding onto an "output" based
        * on user input.
        */
        $output = \'\';

        foreach( $this->networks as $network ) {
            /** 
            * @see An if-if-if logic was chosen due to the fact that the script should continue if a past condition * as not met. The way it works now is "if past condition is not met, skip, verify this one."
            */
            if( $network == \'facebook\' ) {
                $output .= \'<a class="facebook-share share-post-icon" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=\' . get_permalink() . \'"><i class="sf-1"></i></a>\';
            }

            if( $network == \'twitter\' ) {
                $output .= \'<a class="twitter-share share-post-icon" target="_blank" href="https://twitter.com/home?status=Check%20out%20this%20article:%20\' . get_permalink() . \'%20-%20\' . \'"><i class="sf-6"></i></a>\';
            }

            if( $network == \'pinterest\' ) {
                $image = wp_get_attachment_url( get_post_thumbnail_id( $this->post->ID ) );
                $output .= \'<a class="pinterest-share share-post-icon" target="_blank" href="https://pinterest.com/pin/create/button/?url=\' . get_permalink() . \'&media=\' . $image . \'&description=\' . get_the_title() . \'"><i class="sf-5"></i></a>\';
            }

            if( $network == \'gplus\' ) {
                $output .= \'<a class="gplus-share share-post-icon" target="_blank" href="https://plus.google.com/share?url=\' . get_permalink() . \'"><i class="sf-3"></i></a>\';
            }
        }

        return $output;
    }

    public function generate_share_links() {
        /**
        * This function ultimately generates the sharer class itself, using data ingested from *generate_social_output.
        */

        $networks_el = array_intersect( array( \'facebook\', \'twitter\', \'pinterest\', \'gplus\' ), $this->networks );

        if( empty( $networks_el ) ) {
            return new WP_Error( \'empty_networks\', esc_html__( \'No networks were set up.\', \'_s\') );
        } else {

            if ( is_single() ) {
                $output = \'<div class="post-share \' . $this->style . \'">\' . \'<div class="holder">\';
                $output .= $this->generate_social_output();
                $output .= \'</div></div>\';

                if ( \'yes\' == $this->display_it ) {
                    echo $output;
                } else {
                    return $output;
                }

            } else if ( !is_single() && $this->style == \'share-style-1\' ) {
                // If we\'re not on the post page and the style is \'1\', then we know that we should display the share buttons somewhere else, e.g: Homepage.
                $output = \'<div class="post-share share-style-1"><div class="holder">\';
                $output .= $this->generate_social_output();
                $output .= \'</div></div>\';

                if ( \'yes\' == $this->display_it ) {
                    echo $output;
                } else {
                    return $output;
                }
            }
        }
    }
}
在我的帖子页面中,我这样称呼它:

<?php
    (new Post_Share( array( \'facebook\', \'twitter\', \'gplus\', \'pinterest\' ), $post, $style = \'share-style-2\', $display_it = \'yes\' ))->generate_share_links();
    ?>
是相当。。。奥术,下面是全部内容:

<article id="single-post-<?php the_ID(); ?>" <?php post_class(\'single-post\'); ?>>
    <?php
    (new Post_Share( array( \'facebook\', \'twitter\', \'gplus\', \'pinterest\' ), $post, $style = \'share-style-2\', $display_it = \'yes\' ))->generate_share_links();
    ?>
    <header class="single-post-header">
        <div class="single-post-meta">
            <?php echo _s_show_post_info( array( \'author\',\'time\', \'category\' ) ); ?>
        </div><!-- .post-meta -->

        <?php
        the_title( \'<h1 class="single-post-title">\',\'</h1>\' );
        if ( has_category() ) : ?>
            <?php

            $categories = (array) wp_get_post_terms( get_the_ID(), \'category\' );

            if ( !is_wp_error( $categories ) && !empty( $categories) ) { ?>
                <div class="single-post-secondary-meta">
                    <span class="single-post-category-span">posted in
                        <a class="single-post-category" href="<?php echo get_term_link( $categories[0] )?>"><?php echo $categories[0] -> name ?>
                        </a>
                    </span>
                </div><!-- .post-meta-2 -->
            <?php } ?>
        <?php endif; ?>
    </header><!-- .post-header -->

    <?php if ( has_post_thumbnail() ) : ?>
        <?php if ( !has_post_format( $format = array( \'video\', \'audio\') ) ) : ?>
            <div class="single-post-thumbnail">
                <a class="single-post-thumbnail-link" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                    <?php the_post_thumbnail(); ?>
                </a>
            </div><!-- .post-thumbnail -->
        <?php endif; ?>
    <?php endif; ?>

    <div class="single-post-content">
        <?php
            //echo wp_trim_words( get_the_content(), 40, \'...\' );
            the_content();
        ?>
    </div><!-- .post-content -->
</article><!-- #post-<?php the_ID(); ?> -->
<?php 
get_template_part(\'template-parts/individual_post-related-posts\');
?>
我怎样才能更好地初始化它?

我正在寻找:

不使用变量仅初始化类,然后执行->呼叫generate_share_links.

不使用中的双括号(new .. .. )->.

我的选择是什么?

1 个回复
最合适的回答,由SO网友:Radoslav Georgiev 整理而成

您可以避免使用(new ...)-> 通过使用静态方法new 内部实例。

将此与魔法相结合__toString 方法允许您直接回显创建的实例。

下面是如何写的:

<?php
class Post_Share {
    /**
     * Using Post_Share::generate() will directly return the new instance,
     * so (new Post_Share) is not needed.
     */
    public static function generate( $networks = array(), $post, $style, $display = \'no\' ) {
        return new self( $networks, $post, $style, $display );
    }

    /**
     * Calling additional methods can be avoided by echoing the instance.
     */
    public function __toString() {
        // Backup
        $original_display = $this->display_it;
        $this->display_it = false;

        // Generate
        $output = $this->generate_share_links();

        // Restore
        $this->display_it = $original_display;

        return $output;
    }

    // ...your own code
}
这样做后,您可以同时执行以下两项操作:

<?php Post_Share::generate( array( \'facebook\' ), $post, \'share-style-2\' )->generate_share_links() ?>

<?php echo Post_Share::generate( array( \'facebook\' ), $post, \'share-style-2\' ) ?>

这里发生了一些事情:

static 第一个方法中的关键字表示不需要创建类的实例来调用该方法,只需调用类名,后跟双冒号,然后是方法名(例如。Post_share::generate).

  • self 关键字是指当前类的名称。new self 等于new Post_Share.(new ...).
  • __toString 方法在PHP尝试将类转换为字符串时自动调用。当回显类(如示例中所示)并将其连接(“Post\\u Share::generate(…)”时,会发生这种情况更多文本)等

  • 结束

    相关推荐