プラグインでページのどこでも挿入できるcms:idを追加する

どのページでも使用できるcms:idを追加するプラグインを作成してみます。

今回はプラグインの書き方で作成したplugin_baseプラグインに書き足す形で機能の追加を行います。


現在の時刻を出力するタグを作成してみます。

※今回作成するタグは例外としてブロック(ブロクブロック)内とcms:module内では使用できません


/CMSインストールディレクトリ/common/site_include/plugin/plugin_base/plugin_base.php

<?php

class PluginBasePlugin{

	const PLUGIN_ID = "plugin_base";

	function getId(){
		return self::PLUGIN_ID;
	}

	function init(){
		CMSPlugin::addPluginMenu(self::PLUGIN_ID,array(
			"name" => "プラグインの基本構造",
			"type" => Plugin::TYPE_NONE,
			"description" => "",
			"author" => "",
			"url" => "",
			"mail" => "",
			"version" => "1.0"
		));
		
		// 当プラグインが有効であるかを調べる
		if(CMSPlugin::activeCheck(self::PLUGIN_ID)){
			if(defined("_SITE_ROOT_")){
				// 公開側ページの方で動作する拡張ポイントで使用したいものを追加する

				// ページが出力する前の拡張ポイントを利用します。三番目の値の配列のonPageOutputはプラグインのクラスに追加するメソッド名になります
				CMSPlugin::setEvent("onPageOutput", self::PLUGIN_ID, array($this, "onPageOutput"));
			
			}else{
				// 管理画面側の方で動作する拡張ポイントで使用したいものを追加する
			}
		}
	}

	// CMSPlugin::setEventで追加した拡張ポイントの処理のコードを書きます。
	function onPageOutput($obj){
		$obj->createAdd("now", "HTMLLabel", array(
			"soy2prefix" => "cms",
			"text" => date("Y-m-d H:i:s")
		));
	}

	public static function register(){
		$obj = CMSPlugin::loadPluginConfig(self::PLUGIN_ID);
		if(!$obj) $obj = new PluginBasePlugin();
		CMSPlugin::addPlugin(self::PLUGIN_ID, array($obj, "init"));
	}
}

PluginBasePlugin::register();

プラグインで使用できる拡張ポイントについてはhttps://github.com/inunosinsi/soycms/blob/master/cms/common/util/CMSPlugin.class.phpをご覧ください。

onPageOutputの拡張ポイントでは、引数である$objがHTMLPageを継承したクラスで、createAddメソッドを使用することが出来ます。

createAddやHTMLLabelについてはPHPモジュール内でHTMLLabelを使用するに記載があります。


今回のコードでcms:id="now"が使えるようになりました。

onPageOutputについて実際のプラグインで確認したい場合は最初と最後の記事リンク出力プラグイン(プラグインID:first_and_last_entry_link)がおすすめです。

https://github.com/inunosinsi/soycms/blob/master/cms/common/site_include/plugin/first_and_last_entry_link/first_and_last_entry_link.php


追記

onPageOutputの拡張ポイントが実行されるタイミングはCMSPageクラスでブロックの実行が終わった後の

CMSPlugin::callEventFunc('onPageOutput',$this);

になります。

https://github.com/inunosinsi/soycms/blob/master/cms/common/site_include/CMSPage.class.php


追記2

HTMLLabelに関する詳しい記述はSOY2HTMLのHTMLLabelを詳しく見るにあります。

同じカテゴリーの記事