Typecho插件核心代码实现
此前已进行较多铺垫,现在进入核心代码的编写阶段。
分析需求可知,发布文章时需获取当前文章的URL,关键在于从$contents和$class变量中提取该信息。
当前插件类的代码结构如下(注意render方法已更名为send)。
复制代码 代码如下: class BaiduSubmitTest_Plugin implements Typecho_Plugin_Interface {
public static function activate(){ //挂载发布文章和页面的接口 Typecho_Plugin::factory('Widget_Contents_Post_Edit')->finishPublish = array('BaiduSubmitTest_Plugin', 'send'); Typecho_Plugin::factory('Widget_Contents_Page_Edit')->finishPublish = array('BaiduSubmitTest_Plugin', 'send'); return '插件安装成功,请进入设置填写准入密钥'; }
public static function deactivate(){ // do something return '插件卸载成功'; }
public static function config(Typecho_Widget_Helper_Form $form){ $element = new Typecho_Widget_Helper_Form_Element_Text('api', null, null, _t('准入秘钥'), '请登录百度站长平台获取'); $form->addInput($element); }
public static function personalConfig(Typecho_Widget_Helper_Form $form){}
public static function send($contents, $class){ //do something } }
获取URL
获取永久链接需结合路由规则与Typecho_Common::url方法共同生成。
复制代码 代码如下: class BaiduSubmitTest_Plugin implements Typecho_Plugin_Interface {
public static function activate(){ //挂载发布文章和页面的接口 Typecho_Plugin::factory('Widget_Contents_Post_Edit')->finishPublish = array('BaiduSubmitTest_Plugin', 'send'); Typecho_Plugin::factory('Widget_Contents_Page_Edit')->finishPublish = array('BaiduSubmitTest_Plugin', 'send'); return '插件安装成功,请进入设置填写准入密钥'; }
public static function deactivate(){ // do something return '插件卸载成功'; }
public static function config(Typecho_Widget_Helper_Form $form){ //保存接口调用地址 $element = new Typecho_Widget_Helper_Form_Element_Text('api', null, null, _t('接口调用地址'), '请登录百度站长平台获取'); $form->addInput($element); }
public static function personalConfig(Typecho_Widget_Helper_Form $form){}
/** * 准备数据 * @param $contents 文章内容 * @param $class 调用接口的类 * @throws Typecho_Plugin_Exception */ public static function send($contents, $class){
//如果文章属性为隐藏或滞后发布 if( 'publish' != $contents['visibility'] || $contents['created'] > time()){ return; }
//获取系统配置 $options = Helper::options();
//判断是否配置好API if( is_null($options->plugin('BaiduSubmitTest')->api) ){ return; }
//获取文章类型 $type = $contents['type'];
//获取路由信息 $routeExists = (NULL != Typecho_Router::get($type));
//生成永久连接 $path_info = $routeExists ? Typecho_Router::url($type, $contents) : '#'; $permalink = Typecho_Common::url($path_info, $options->index); } }
代码中已添加注释,此处不再赘述细节。
至此,我们已成功获取文章的永久链接,下一步将是向百度服务器发送数据。
本节内容结束!