在模板中使用插件类

时间:2012-03-07 作者:nandac

我正在编写一个插件,向朋友发送邀请,点击链接时会打开一个表单。我按照@toscho的报告Breaked Video插件中给出的代码封装了类中的所有函数。相关代码如下:

/*
Plugin Name: Send Invitation
Plugin URI: http://w3boutique.net
Description: Emails a the link of the current page to a friend
Author: Nandakumar Chandrasekhar
Version: 0.1
Author URI: http://w3boutique.net/about-nanda.html
License: GPL2
*/

// include() or require() any necessary files here

// Settings and/or Configuration Details go here
define(\'SEND_INVITATION_MIN_WORDPRESS_VERSION\', \'3.1.1\');

define(\'SEND_INVITATION_PLUGIN_URL\', plugins_url(\'\', __FILE__));

add_action( \'init\', array( \'SendInvitation\', \'nc_sendinvitation_init\' ) );

class SendInvitation {

    protected $nonce_name = \'nc_sendinvitation\';
    protected $post_url = \'\';

    public static function nc_sendinvitation_init() {
        new self;
    }

    public function __construct() {
        add_action( \'init\', array(&$this, \'nc_sendinvitation_head\' ));
        add_action( \'init\', array(&$this,  \'nc_sendinvitation_check_wordpress_version\' ));
       add_action( \'init\', array(&$this, \'nc_sendinvitation_form_action\' ));
       //$this->post_url = $this->nc_sendinvitation_get_post_url();
   }

   public function nc_sendinvitation_head() {
       wp_enqueue_script( \'jquery\' );
       wp_enqueue_script( \'send_invitation_js\',
        plugins_url( \'js/send-invitation.js\', __FILE__ ),
        array( \'jquery\' ) );

       wp_enqueue_style( \'send_invitation_css\',
        plugins_url( \'css/send-invitation.css\', __FILE__ ) );
   }

   public function nc_sendinvitation_check_wordpress_version() {
       global $wp_version;

       $exit_msg = \'Send Invitation requires version \'
    . SEND_INVITATION_MIN_WORDPRESS_VERSION
    . \'or newer <a href="http://codex.wordpress.org/Upgrading_WordPress">Please
update!</a>\';

       if ( version_compare( $wp_version, SEND_INVITATION_MIN_WORDPRESS_VERSION, \'<\') )
       {
            exit( $exit_msg );
       }
   }

   public function nc_sendinvitation_form_action() {

        $action = \'\';
        if ( $_SERVER[\'REQUEST_METHOD\'] != \'POST\' )
        {
             $action = $this->nc_sendinvitation_get_form();
        }
        else if ( $_SERVER[\'REQUEST_METHOD\'] == \'POST\' ) {
            $action = $this->nc_sendinvitation_handle_submit();
        }
        return $action;
   }

   public function nc_sendinvitation_get_form() {
       // Start the output buffer, prevents content being output directly into
       // script, instead it is stored in a buffer which can then be flushed
       // to allow the include file to be stored in a variable
       // See http://www.codingforums.com/showthread.php?t=124537
       ob_start();
       include(\'send-invitation-form.php\');
       $send_invitation_link = ob_get_clean();

       return $send_invitation_link;
   }

   public function nc_sendinvitation_handle_submit() {
         if ( isset( $_POST[\'form_type\'] ) && ( $_POST[\'form_type\'] == \'nc_sendinvitation\' ) ) {
            $to = \'[email protected]\';
            $subject = \'Invitation to SwanLotus\';
            $message = \'Navanitachora invites you to take a look at this link\';
            wp_mail($to, $subject, $message);
            $result = \'Email was sent successfully\';
    }
    else {
        $result = $this->nc_sendinvitation_get_form();
    }
    return $result;
}

public function nc_sendinvitation_get_post_url() {
    global $post;
    $blog_id = get_option(\'page_for_posts\');
    $post_id = \'\';
    if (is_home($blog_id)) {
        $post_id = $blog_id;
    } else {
        $post_id = $post->ID;
    }

    return get_permalink($post_id);
}
}
/* End of File */
?>
我不知道如何在模板中使用这个类,以便显示表单。我知道我需要实例化这个类,但我不确定将代码放在哪里,以及如何访问对象,以便在模板中使用它。我有OOP的知识,但以前没有在这种情况下使用过它,需要一点循序渐进的指导。

非常感谢。

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

在不知道对象的情况下使用类的最佳方法是action. 在加载演示文稿的主题文件之前注册操作,WordPress将处理其余操作。

示例代码:

<?php # -*- coding: utf-8 -*-
/**
 * Plugin Name: Plugin Action Demo
 */
add_action( \'init\', array ( \'Plugin_Action_Demo\', \'init\' ) );

class Plugin_Action_Demo
{
    /**
     * Creates a new instance.
     *
     * @wp-hook init
     * @see    __construct()
     * @return void
     */
    public static function init()
    {
        new self;
    }

    /**
     * Register the action. May do more magic things.
     */
    public function __construct()
    {
        add_action( \'plugin_action_demo\', array ( $this, \'print_foo\' ), 10, 1 );
    }

    /**
     * Prints \'foo\' multiple $times.
     *
     * Usage:
     *    <code>do_action( \'plugin_action_demo\', 50 );</code>
     *
     * @wp-hook plugin_action_demo
     * @param int $times
     * @return void
     */
    public function print_foo( $times = 1 )
    {
        print str_repeat( \' foo \', (int) $times );
    }
}
现在你可以打电话了do_action( \'plugin_action_demo\', 50 ); 在您的主题或其他插件的某个地方,您不必再关心类的内部工作。

如果你停用插件,你仍然是安全的:WordPress只会忽略未知的操作和do_action() 不会有什么害处。另外,其他插件可以删除或替换该操作,因此您已经用一个add_action().

您还可以构建一个单例:

<?php # -*- coding: utf-8 -*-
/**
 * Plugin Name: Plugin Singleton Demo
 */
class Plugin_Singleton_Demo
{
    protected static $instance = NULL;

    /**
     * Creates a new instance if there isn\'t one.
     *
     * @wp-hook init
     * @return object
     */
    public static function get_instance()
    {

        NULL === self::$instance and self::$instance = new self;
        return self::$instance;
    }

    /**
     * Not accessible from the outside.
     */
    protected function __construct() {}

    /**
     * Prints \'foo\' multiple $times.
     *
     * @param int $times
     * @return void
     */
    public function print_foo( $times = 1 )
    {
        echo str_repeat( \' foo \', (int) $times );
    }
}
现在print_foo() 可通过以下方式访问:

Plugin_Singleton_Demo::get_instance()->print_foo();
我不推荐单例模式。它有一些serious drawbacks.

结束

相关推荐

simply loop through posts

我知道这是一个真正的新手问题,但我似乎无法从帖子中获得循环。它所做的只是从页面本身中提取。我制作了一个模板并添加了循环。<?php if( have_posts() ) { while( have_posts() ) { the_post(); ?> <h2><?php the_title(); ?></h2> <?php } } ?>