规则之树

typecho二级开发实例,新增Widget接口

一直在弄typecho的二次开发,其实就是为了做好一个分配的项目,改了typecho大量的更新文件,特别是Widget里面,在想办法新增接口。对于这个项目而言,typecho的功能太少了,所以明显的有些适应不来,我最先的操作就是在参考官方代码的基础上自己添加接口。所以,目前已经实现了评论数排序,随机排序,按字数排序三个接口,并且在页面成功的调用,这个过程没有修改typecho本身的任何文件,只是在文件夹里自己加了三个文件,在里面写class对象。
我相信这个过程会很有参考价值,在碰到数据调用问题的时候,与其在模板或者插件的控制器写一堆东西,还不如在typecho的Widget里丢文件,本身就不会影响到什么,也不会因为程序更新覆盖。

主要是在/var/Widget/Contents/Post这个路径里增加文件。

按评论数排序,新建文件Comments.php:

<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
class Widget_Contents_Post_Comments extends Widget_Abstract_Contents
{
    public function execute()
    {
        $this->parameter->setDefault(array('pageSize' => $this->options->postsListSize));
        $this->db->fetchAll($this->select()
        ->where('table.contents.status = ?', 'publish')
        ->where('table.contents.created < ?', $this->options->time)
        ->where('table.contents.type = ?', 'post')
        ->order('commentsNum', Typecho_Db::SORT_DESC)
        ->limit($this->parameter->pageSize), array($this, 'push'));
    }
}

调用接口名为Widget_Contents_Post_Comments,案例如下:

<?php $this->widget('Widget_Contents_Post_Comments','pageSize=10')->to($Comments);while($Comments->next()): ?>
循环内代码
<?php endwhile; ?>

随机排序,新建文件Rand.php

<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
class Widget_Contents_Post_Rand extends Widget_Abstract_Contents
{
    public function execute()
    {
    $this->parameter->setDefault(array('pageSize' => $this->options->postsListSize));
        $this->db->fetchAll($this->select()
        ->where('table.contents.status = ?', 'publish')
        ->where('table.contents.created < ?', $this->options->time)
        ->where('table.contents.type = ?', 'post')
        ->order('RAND()', Typecho_Db::SORT_DESC)
        ->limit($this->parameter->pageSize), array($this, 'push'));
    }
}

调用接口名为Widget_Contents_Post_Rand,案例如下:

<?php $this->widget('Widget_Contents_Post_Rand','pageSize=10')->to($Rand);while($Rand->next()): ?>
循环内代码
<?php endwhile; ?>

按字数排序,新增文件Size.php

<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
class Widget_Contents_Post_Size extends Widget_Abstract_Contents
{
    public function execute()
    {
        $this->parameter->setDefault(array('pageSize' => $this->options->postsListSize));
        $this->db->fetchAll($this->select()
        ->where('table.contents.status = ?', 'publish')
        ->where('table.contents.created < ?', $this->options->time)
        ->where('table.contents.type = ?', 'post')
        ->order('LENGTH(text)', Typecho_Db::SORT_DESC)
        ->limit($this->parameter->pageSize), array($this, 'push'));
    }
}

调用接口名为Widget_Contents_Post_Size,案例如下:

<?php $this->widget('Widget_Contents_Post_Size','pageSize=10')->to($Size);while($Size->next()): ?>
循环内代码
<?php endwhile; ?>

以上就是三个接口的实现方法,经过实际的测试没有任何问题,且已经部分整合到github上的typecho-love项目,目前网上给出的很多数据调用方法局限性很大,无法灵活的控制,而且占用很多代码量,所以用此方法解决可以很好的解决后续开发时间,并且对后续的代码调用带来很好的灵活性。

规则之树版权所有,转载请注明来源,标明作者及原文链接

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »