前言
趁著有時間豪椿,學習一波插件,插件是個好東西携栋,希望人人都會寫搭盾。
環(huán)境
語言:php5.6
框架:ThinkCMF
教程開始
1. 編寫插件
- 創(chuàng)建插件配置文件:創(chuàng)建插件主類文件:在根目錄的plugins文件夾下創(chuàng)建一個HelloWorld文件夾,在HelloWrold文件夾下面 創(chuàng)建 config.php 文件
config.php代碼如下
<?php
/**
* Created by PhpStorm.
* User: **
* Date: 2017/8/14
* Time: 上午 10:27
*/
return array(
'text'=>array(
'title' => '文本:', // 表單的label標題
'type' => 'text',// 表單的類型:text,password,textarea,checkbox,radio,select等
'value' => 'hello,ThinkCMF!',// 表單的默認值
'tip' => '這是文本組件的演示' //表單的幫助提示
)
);
- 在HelloWrold文件夾下面婉支,創(chuàng)建一個繼承與Plugin的HelloWorldPlugin類鸯隅,該類的命名空間為plugins\HelloWorld。
HelloWorldPlugin類的代碼如下
namespace plugins\HelloWorld;
use Common\Lib\Plugin;
class HelloWorldPlugin extends Plugin
{
//插件的配置信息
public $info = array(
'name'=>'HelloWorld',//Demo插件英文名,改成你的插件英文就行了
'title'=>'HelloWorld插件',
'description'=>'HelloWorld插件',
'status'=>1,
'author'=>'ThinkCMF',
'version'=>'1.0'
);
//安裝方法必須實現(xiàn)
public function install()
{
//安裝成功返回true蝌以,失敗false
return true;
// TODO: Implement install() method.
}
//卸載方法必須實現(xiàn)
public function uninstall()
{
//卸載成功返回true炕舵,失敗false
return true;
// TODO: Implement uninstall() method.
}
//實現(xiàn)的show鉤子方法
public function show() {
//獲取config文件里面的text數(shù)組
$config=$this->getConfig('text');
//賦值
$this->assign($config);
//載入模板index.html,傳入?yún)?shù)不要寫.html后綴
$this->display('index');
}
}
- 創(chuàng)建模板文件:在HelloWorld文件夾下面創(chuàng)建一個View文件夾跟畅,在View文件下創(chuàng)建一個index.html文件
index.html文件 代碼如下
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ThinkCMF插件演示首頁</title>
</head>
<body>
<h1 align="center">{$text}</h1>
</body>
</html>
- 創(chuàng)建外部訪問文件:在HelloWorld文件夾下面創(chuàng)建一個Contrller文件夾咽筋,在Contrller文件下創(chuàng)建一個所需文件,本教程用不到就不創(chuàng)建徊件。
2.添加鉤子
- 打開 根目錄/application/Portal/hooks.php 添加 show 方法
代碼如下:
<?php
return array(
'show',
);
3.使用教程
登錄 thinkcmf的后臺奸攻,選擇擴展工具,點擊插件管理虱痕,如下圖
Paste_Image.png
點擊安裝睹耐,安裝HelloWorld插件,如下圖
Paste_Image.png
- 調(diào)用方法 hook('鉤子方法') 如下
hook('show');
顯示結果
Paste_Image.png
注意事項
如果修改了鉤子部翘,即在hooks.php里面添加了鉤子或者刪除了鉤子方法硝训,必須到ThinkCMF后臺去更新或者重裝插件
-
查看插件的鉤子方法,打開后臺在插件管理里面的鉤子列里面方法就是新思,可以使用的鉤子方法 如下圖的show方法窖梁。
Paste_Image.png 修改了插件的配置信息即在主文件里(HelloWorldPlugin )的 $info 數(shù)組, 也要去后臺更新插件或者重裝插件夹囚。