当前位置: 首页 > 编程文章 >

Yii视图整合KindEditor扩展的方法

Yii视图整合KindEditor扩展的方法

作者:苏川时间:2026-02-20 12:29:02浏览:270

针对Yii框架中KindEditor版本过旧的问题,本文介绍如何自定义扩展以整合新版编辑器。通过创建KEditor、KEditorManage和KEditorUpload三个核心类,并在config/main.php中配置上传路径及actions路由,实现在视图中通过textareaOptions或JS属性灵活调用KindEditor,支持文件浏览与上传功能。

本文目录展开

KindEditor在Yii中的扩展整合方案

本实例详细解析了在Yii视图层中集成KindEditor编辑器的具体实现方案,旨在为开发者提供可参考的实践步骤。

鉴于官方提供的KindEditor版本较为陈旧,此处演示如何自行构建一个更新颖的扩展组件。首先需在protected/extensions目录下新建KEditor文件夹作为资源根目录,其中keSource子目录用于存放KindEditor源码。随后建立三个核心类:KEditor作为主扩展入口,KEditorManage负责服务器文件浏览接口,而KEditorUpload则专门处理文件上传逻辑。

以下是KEditor主类的代码实现细节。


<?php
class KEditor extends CWidget{
    /*
    * TEXTAREA输入框的属性,保证js调用KE失败时,文本框的样式。
    */
    public $textareaOptions=array();
    /*
    * 编辑器属性集。
    */
    public $properties=array();
    /*
    * TEXTAREA输入框的name,必须设置。
    * 数据类型:String
    */
    public $name;
    /*
    * TEXTAREA的id,可为空
    */
    public $id;
    public $model;
    public $baseUrl;
    public static function getUploadPath(){
        $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';
        if(isset(Yii::app()->params->uploadPath)){
            return Yii::getPathOfAlias('webroot').str_replace(
            '/',DIRECTORY_SEPARATOR,
            Yii::app()->params->
            uploadPath);
        }
        return Yii::app()->getAssetmanager()
        ->getPublishedPath($dir).DIRECTORY_SEPARATOR.'upload';
    }
    public static function getUploadUrl(){
        $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';
        if(isset(Yii::app()->params->uploadPath)){
            return Yii::app()->baseUrl.Yii::app()->params->uploadPath;
        }
        return Yii::app()->getAssetManager()->publish($dir).'/upload';
    }
    public function init(){
        if($this->name===null)
        throw new CException(Yii::t('zii','The id property cannot be empty.'));
        $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';
        $this->baseUrl=Yii::app()->getAssetManager()->publish($dir);
        $cs=Yii::app()->getClientScript();
        $cs->registerCssFile($this->baseUrl.'/themes/default/default.css');
        if(YII_DEBUG) $cs->registerScriptFile($this->baseUrl.'/kindeditor.js');
        else $cs->registerScriptFile($this->baseUrl.'/kindeditor-min.js');
    }
    public function run(){
        $cs=Yii::app()->getClientScript();
        $textAreaOptions=$this->gettextareaOptions();
        $textAreaOptions['name']=CHtml::resolveName($this->model,$this->name);
        $this->id=$textAreaOptions['id']=CHtml::getIdByName($textAreaOptions['name']);
        echo CHtml::activeTextArea($this->model,$this->name,$textAreaOptions);
        $properties_string = CJavaScript::encode($this->getKeProperties());
        $js=<<<EOF
        KindEditor.ready(function(K) {
            var editor_$this->id = K.create('#$this->id',
            $properties_string
            );
        });
        EOF;
        $cs->registerScript('KE'.$this->name,$js,CClientScript::POS_HEAD);
    }
    public function gettextareaOptions(){
        //允许获取的属性
        $allowParams=array('rows','cols','style');
        //准备返回的属性数组
        $params=array();
        foreach($allowParams as $key){
            if(isset($this->textareaOptions[$key]))
            $params[$key]=$this->textareaOptions[$key];
        }
        $params['name']=$params['id']=$this->name;
        return $params;
    }
    public function getKeProperties(){
        $properties_key=array(
        'width',
        'height',
        'minWidth',
        'minHeight',
        'items',
        'noDisableItems',
        'filterMode',
        'htmlTags',
        'wellFormatMode',
        'resizeType',
        'themeType',
        'langType',
        'designMode',
        'fullscreenMode',
        'basePath',
        'themesPath',
        'pluginsPath',
        'langPath',
        'minChangeSize',
        'urlType',
        'newlineTag',
        'pasteType',
        'dialogAlignType',
        'shadowMode',
        'useContextmenu',
        'syncType',
        'indentChar',
        'cssPath',
        'cssData',
        'bodyClass',
        'colorTable',
        'afterCreate',
        'afterChange',
        'afterTab',
        'afterFocus',
        'afterBlur',
        'afterUpload',
        'uploadJson',
        'fileManagerJson',
        'allowPreviewEmoticons',
        'allowImageUpload',
        'allowFlashUpload',
        'allowMediaUpload',
        'allowFileUpload',
        'allowFileManager',
        'fontSizeTable',
        'imageTabIndex',
        'formatUploadUrl',
        'fullscreenShortcut',
        'extraFileUploadParams',
        );
        //准备返回的属性数组
        $params=array();
        foreach($properties_key as $key){
            if(isset($this->properties[$key]))
            $params[$key]=$this->properties[$key];
        }
        return $params;
    }
}
</code></pre>
接下来展示KEditorManage类的代码,该类用于处理文件管理相关的JSON请求。
<pre class="brush:php;"><code class="language-php">
<?php
class KEditorManage extends CAction{
    public function run(){
        Yii::import('ext.KEditor.KEditor');
        $root_path=KEditor::getUploadPath().'/';
        $root_url=KEditor::getUploadUrl().'/';
        //图片扩展名
        $ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
        //目录名
        $dir_name = empty($_GET['dir']) ? '' : trim($_GET['dir']);
        if (!in_array($dir_name, array('', 'image', 'flash', 'media', 'file'))) {
            echo "Invalid Directory name.";
            exit;
        }
        if ($dir_name !== '') {
            $root_path .= $dir_name . "/";
            $root_url .= $dir_name . "/";
            if (!file_exists($root_path)) {
                mkdir($root_path);
            }
        }
        //根据path参数,设置各路径和URL
        if (empty($_GET['path'])) {
            $current_path = realpath($root_path) . '/';
            $current_url = $root_url;
            $current_dir_path = '';
            $moveup_dir_path = '';
        } else {
            $current_path = realpath($root_path) . '/' . $_GET['path'];
            $current_url = $root_url . $_GET['path'];
            $current_dir_path = $_GET['path'];
            $moveup_dir_path = preg_replace('/(.*?)[^\/]+\/$/', '$1', $current_dir_path);
        }
        echo realpath($root_path);
        //排序形式,name or size or type
        $order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);
        //不允许使用..移动到上一级目录
        if (preg_match('/\.\./', $current_path)) {
            echo 'Access is not allowed.';
            exit;
        }
        //最后一个字符不是/
        if (!preg_match('/\/$/', $current_path)) {
            echo 'Parameter is not valid.';
            exit;
        }
        //目录不存在或不是目录
        if (!file_exists($current_path) || !is_dir($current_path)) {
            echo 'Directory does not exist.';
            exit;
        }
        //遍历目录取得文件信息
        $file_list = array();
        $handle = new DirectoryIterator($current_path);
        $i=0;
        foreach($handle as $file){
            if($file->isDot()) continue;
            if($file->isDir()){
                $file_list[$i]['is_dir'] = true; //是否文件夹
                $file_list[$i]['has_file'] = (count(scandir($file->getPath())) > 2); //文件夹是否包含文件
                $file_list[$i]['filesize'] = 0; //文件大小
                $file_list[$i]['is_photo'] = false; //是否图片
                $file_list[$i]['filetype'] = ''; //文件类别,用扩展名判断
            }else{
                $file_list[$i]['is_dir'] = false;
                $file_list[$i]['has_file'] = false;
                $file_list[$i]['filesize'] = $file->getSize();
                $file_list[$i]['dir_path'] = '';
                $file_ext = $file->getExtension();
                $file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);
                $file_list[$i]['filetype'] = $file_ext;
            }
            $file_list[$i]['filename'] = $file->getFilename(); //文件名,包含扩展名
            $file_list[$i]['datetime'] = date('Y-m-d H:i:s', $file->getMTime());
            $i++;
        }
        usort($file_list, array($this,'cmp_func'));
        $result = array();
        //相对于根目录的上一级目录
        $result['moveup_dir_path'] = $moveup_dir_path;
        //相对于根目录的当前目录
        $result['current_dir_path'] = $current_dir_path;
        //当前目录的URL
        $result['current_url'] = $current_url;
        //文件数
        $result['total_count'] = count($file_list);
        //文件列表数组
        $result['file_list'] = $file_list;
        //输出JSON字符串
        header('Content-type: application/json; charset=UTF-8');
        echo CJSON::encode($result);
        exit;
    }
    //排序
    public function cmp_func($a, $b) {
        global $order;
        if ($a['is_dir'] && !$b['is_dir']) {
            return -1;
        } else if (!$a['is_dir'] && $b['is_dir']) {
            return 1;
        } else {
            if ($order == 'size') {
                if ($a['filesize'] > $b['filesize']) {
                    return 1;
                } else if ($a['filesize'] < $b['filesize']) {
                    return -1;
                } else {
                    return 0;
                }
            } else if ($order == 'type') {
                return strcmp($a['filetype'], $b['filetype']);
            } else {
                return strcmp($a['filename'], $b['filename']);
            }
        }
    }
}
?>

随后是KEditorUpload类的代码,用于接收并处理前端传来的上传文件数据。


<?php
class KEditorUpload extends CAction{
    public function run(){
        $dir=isset($_GET['dir'])?trim($_GET['dir']):'file';
        $ext_arr = array(
        'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
        'flash' => array('swf', 'flv'),
        'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
        'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
        );
        if(empty($ext_arr[$dir])){
            echo CJSON::encode(array('error'=>1,'message'=>'目录名不正确。'));
            exit;
        }
        $originalurl='';
        $filename='';
        $date=date('Ymd');
        $id=0;
        $max_size=2097152; //2MBs
        $upload_image=CUploadedFile::getInstanceByName('imgFile');
        Yii::import('ext.KEditor.KEditor');
        $upload_dir=KEditor::getUploadPath().'/'.$dir;
        if(!file_exists($upload_dir)) mkdir($upload_dir);
        $upload_dir=$upload_dir.'/'.$date;
        if(!file_exists($upload_dir)) mkdir($upload_dir);
        $upload_url=KEditor::getUploadUrl().'/'.$dir.'/'.$date;
        if(is_object($upload_image) && get_class($upload_image)==='CUploadedFile'){
            if($upload_image->size > $max_size){
                echo CJSON::encode(array('error'=>1,'message'=>'上传文件大小超过限制。'));
                exit;
            }
            //新文件名
            $filename=date("YmdHis").'_'.rand(10000, 99999);
            $ext=$upload_image->extensionName;
            if(in_array($ext, $ext_arr[$dir]) === false){
                echo CJSON::encode(array('error'=>1,'message'=>"上传文件扩展名是不允许的扩展名。\n只允许".implode(',',$ext_arr[$dir]).'格式。'));
                exit;
            }
            $uploadfile=$upload_dir.'/'.$filename.'.'.$ext;
            $originalurl=$upload_url.'/'.$filename.'.'.$ext;
            $upload_image->saveAs($uploadfile);
            echo CJSON::encode(array('error'=>0,'url'=>$originalurl));
        }else{
            echo CJSON::encode(array('error'=>1,'message'=>'未知错误'));
        }
    }
}
</code></pre>
在config/main.php配置文件中,需要明确指定上传文件的存储位置,以便系统正确保存资源。
<pre class="brush:php;"><code class="language-php">
'params'=>array(
// this is used in contact page
'adminEmail'=>'webmaster@example.com',
'uploadPath'=>'/upload', //添加这句,upload为存放文件文件夹的名字,自己定义,这里是放在根目录的upload文件夹
</code></pre>
同时,必须在控制器中设置用于接收文件和浏览服务器文件的Action路由,确保前后端交互畅通。
<pre class="brush:php;"><code class="language-php">
public function actions()
{
    return array(
    //在actions下的return array添加下面两句,没有actions的话自己添加
    'upload'=>array('class'=>'application.extensions.KEditor.KEditorUpload'),
    'manageJson'=>array('class'=>'application.extensions.KEditor.KEditorManage'),
    );
}
</code></pre>
最后在视图模板中引入并使用该扩展,完成编辑器的渲染。
<pre class="brush:php;"><code class="language-php">
<?php $this->widget('ext.KEditor.KEditor',array(
'model'=>$model, //传入form model
'name'=>'content', //设置name
'properties'=>array(
//设置接收文件上传的action
'uploadJson'=>'/admin/default/upload',
//设置浏览服务器文件的action,这两个就是上面配置在/admin/default的
'fileManagerJson'=>'/admin/default/manageJson',
'newlineTag'=>'br',
'allowFileManager'=>true,
//传值前加js:来标记这些是js代码
'afterCreate'=>"js:function() {
K('#ChapterForm_all_len').val(this.count());
K('#ChapterForm_word_len').val(this.count('text'));
}",
'afterChange'=>"js:function() {
K('#ChapterForm_all_len').val(this.count());
K('#ChapterForm_word_len').val(this.count('text'));
}",
),
'textareaOptions'=>array(
'style'=>'width:98%;height:400px;',
)
));
?>

使用textareaOptions参数可控制textarea的尺寸与样式,目前仅支持rows、cols和style属性。properties参数的各项配置与JavaScript初始化KindEditor时的选项一致,原有支持的项均可在此处进行设置,确保行为与原生JS配置相同。


var editor1 = K.create('#editor_modelname_name', {
  uploadJson : "/admin/default/upload",
  fileManagerJson : "/admin/default/manageJson",
  newlineTag : "br",
  allowFileManager : true,
  afterCreate : function() {
    K('#ChapterForm_all_len').html(this.count());
    K('#ChapterForm_word_len').html(this.count('text'));
  },
  afterChange : function() {
    K('#ChapterForm_all_len').html(this.count());
    K('#ChapterForm_word_len').html(this.count('text'));
  }
});

希望上述关于基于Yii框架的PHP程序设计中KindEditor整合的内容,能为各位开发者带来实际帮助。

上一篇
PHP购物车类实现详解:从Session生成到商品管理

本文通过一个完整的PHP购物车类实例,详细解析了基于Session和Cookie的购物车ID生成机制,以及利用MySQL数据库进行商品增删改查的核心逻辑。文章涵盖了check_item、add_item、delete_item等关键方法的实现细节,展示了如何构建二维数组以存储和返回购物车商品的详细信息及总价。

下一篇
PHP解析URL的三种常用函数:pathinfo、parse_url与basename

本文介绍在PHP中利用pathinfo()、parse_url()和basename()三个函数解析URL的方法。pathinfo()用于提取文件路径、文件名及后缀等结构信息;parse_url()将URL拆分为协议、主机、路径、查询参数和锚点等组件;basename()则直接获取URL中的文件名部分。通过具体代码示例展示各函数的输出结果,帮助开发者根据需求选择合适的解析方式。

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,034
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,018
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,017
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,013
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,013

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。