26
eZ Publish extension 開発 チュートリアル (原著: An Introduction to Developing eZ Publish ExtensionseZ Publish extension 開発チュートリアル (原文: An Introduction to Developing eZ Publish Extensions) 著者:Felix Woldt , Jérôme Vieilledent 翻訳:藤田 拓(コトトイ・ファクトリーeZ Publish extension 開発 チュートリアル ......................................................................................... 1 このチュートリアルを読み進める上での前提....................................................................................... 2 何ができるようになるか? ................................................................................................................... 2 eZ Publish extension とは? ..................................................................................................................... 3 extension でできること......................................................................................................................... 3 新しい extension を作成 ........................................................................................................................... 4 チュートリアルのために予め用意しておく環境 ................................................................................... 4 extension の設定.................................................................................................................................... 4 extension の初期知識 ................................................................................................................................ 6 ビューリスト ......................................................................................................................................... 6 extension の有効化.................................................................................................................................... 9 権限管理システム .................................................................................................................................. 9 テンプレート・システム......................................................................................................................... 11 ビューの作成........................................................................................................................................... 14 GET / POST ........................................................................................................................................ 14 データベースへのアクセス ..................................................................................................................... 16 テンプレート・フェッチ機能 ................................................................................................................. 20 テンプレート・オペレータ ..................................................................................................................... 22 INI ファイル ............................................................................................................................................ 25 最後に ..................................................................................................................................................... 26 Resources ........................................................................................................................................... 26 eZ Publish を使えば、PHP コーディングによるカスタマイズをすることなく、ほとんどの CMS 要件に

eZ Publishのextension開発チュートリアル

Embed Size (px)

DESCRIPTION

2008年に最初に執筆されその後2010年にeZ Publish4.x用に描き直されたFelix Woldtの「An Introduction to Developing eZ Publish Extensions」をFelixの許可をもらい日本語訳しました。 eZ Publishのextension開発まわりのオフィシャルドキュメントはAPIドキュメンテーションくらいしかないともいえるので、この記事は取っ掛かりとして有用です。

Citation preview

Page 1: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

eZ Publishの extension開発チュートリアル (原文: An Introduction to Developing eZ Publish Extensions)

著者:Felix Woldt , Jérôme Vieilledent 翻訳:藤田 拓(コトトイ・ファクトリー)

eZ Publishの extension開発 チュートリアル ......................................................................................... 1

このチュートリアルを読み進める上での前提 ....................................................................................... 2

何ができるようになるか? ................................................................................................................... 2

eZ Publish extensionとは? ..................................................................................................................... 3

extensionでできること ......................................................................................................................... 3

新しい extensionを作成 ........................................................................................................................... 4

チュートリアルのために予め用意しておく環境 ................................................................................... 4

extensionの設定 .................................................................................................................................... 4

extensionの初期知識 ................................................................................................................................ 6

ビューリスト ......................................................................................................................................... 6

extensionの有効化 .................................................................................................................................... 9

権限管理システム .................................................................................................................................. 9

テンプレート・システム ......................................................................................................................... 11

ビューの作成 ........................................................................................................................................... 14

GET / POST ........................................................................................................................................ 14

データベースへのアクセス ..................................................................................................................... 16

テンプレート・フェッチ機能 ................................................................................................................. 20

テンプレート・オペレータ ..................................................................................................................... 22

INIファイル ............................................................................................................................................ 25

最後に ..................................................................................................................................................... 26

Resources ........................................................................................................................................... 26

eZ Publishを使えば、PHPコーディングによるカスタマイズをすることなく、ほとんどの CMS要件に

Page 2: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

対応することができます。しかし、eZ Publish実装者は経験を積むにつれ、案件でよく必要となる特別な機能を見つけることとなり、その対応のために extensionを開発するようになるのです。

(このチュートリアルは 2008年 1月 21日に公開されましたが、eZ Publish 4.xに対応した内容とするため、2010年 12月 10日に改訂しました。)

このチュートリアルでは extensionの書き方の基本がわかるように、勘所を掴むための簡単なサンプルを使っています。

このチュートリアルを読み進める上での前提

l eZ Publish 4.x をインストールした環境

l eZ Publishの構造についての基本的な理解

l PHP, SQL, MySQL, HTMLの基本的な知識

何ができるようになるか?

このチュートリアルで簡単な extensionの作成や設定の仕方を学べます。かつ、eZ Publish フレームワークでどう開発を行うか?をお見せします。

Page 3: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

eZ Publish extensionとは?

extensionのサンプルにとりかかる前に、extensionの概要と構造について説明します。

extensionを作成すると eZ Publishの機能追加、または既存機能の拡張を行うことができます。extensionを利用により eZ Publishの本体ファイルを変更することなく、eZ Publishのコア機能を拡張することができます。そのため、eZ Publishのバージョンアップの際に extension部分を上書きすることなく、eZ Publishのバージョンアップ作業を行うことができます。

extensionでできること

l ウェブサイト / サイトアクセス毎のデザインの管理

l 新しいビューや新しいテンプレート・フェッチ機能を追加するためのカスタムモジュールの作成

l カスタムテンプレート・オペレータによるテンプレートシステムの拡張

l 新しいイベント、データタイプ、ログインハンドラーのプログラム

eZ Publishの Extensionは次の表 1で示されるようなディレクトリ構造で構成されます。

extension サブディレクトリ ディレクトリで管理する内容

actions/ フォームの新しいアクション

autoloads/ 新規テンプレート・オペレータの定義

datatypes/ 新規データタイプの定義

design/ デザインに関連するファイル(*.tpl, *.css, *.jpg, *.js ...)

eventtypes/ カスタム・ワークフロー・イベント

modules/ 1つ以上のモジュール/ビューやテンプレート・フェッチ機能等

settings/ コンフィグ・ファイル(*.ini, *.ini.append.php)

translations/ 翻訳ファイル(*.ts)

表 1:eZ Publish 4.x extensionの標準ディレクトリ構造

上記のようなディレクトリ構造は一例です。実際のディレクトリ構造は extensionのタイプ・目的によって異なってきます。いくつかのディレクトリは必要ない場合もあります。例えば、テンプレート・オペレータのための extensionでは autoloads/と settings/といった2つのディレクトリがあれば充分です。また、モジュールのための extensionの場合は modules/、settings/が必要で、かつ、design/も利用する場合があります。

Page 4: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

新しい extensionを作成

さて、今回は eZ Publishの extension開発における基礎を学ぶために、「jacextension」というサンプルを用意しました。このサンプルを利用して extension作成のステップを進めつつ、eZ Publishフレームワークにおける基本的な PHPクラスを理解していきましょう。

このチュートリアルで取り上げる内容:

l データベースへのアクセス(eZ フレームワーク -- class eZPersistentObject)

l .ini ファイル上の設定記述へのアクセス(eZ フレームワーク – class eZINI)

l GET値や POSTのセッション値へのアクセス(eZ フレームワーク - class eZHTTPTool)

l カスタムデバッグメッセージやログ・ファイルの作成(eZ フレームワーク - class eZDebug)

l モジュールの新規ビューにおける権限システムの利用

l 新規テンプレート・フェッチ機能や新規テンプレート・オペレータによるテンプレート・システムの拡張

チュートリアルのために予め用意しておく環境

このチュートリアルを進めるにあたり、eZ Publishを正しくインストールしてください(最新バージョンはこちらにあります)。 その際、eZ Publish Setup Wizardにおいて、Siteaccess Configurationでは「URL」を選択し、そしてサイトのタイプでは「Plain」を選択してください。

インストールすると「plain_site」と「plain_site_admin」の2つのサイトアクセスができます。URLは下記のようになります。

http://localhost/ez/index.php/plain_site (ユーザー用) http://localhost/ez/index.php/plain_site_admin (管理者用) (localhost/ez/ は eZ Publishをインストールしたルートパスです。)

extensionの設定

次に「jacextension」と名付けた新規 extensionを作成して有効化してみましょう。この extensionではビューリスト機能を持つ list.phpが稼働する「modul1」という名前の1つのモジュールが含まれます。

上記 extension作成のために、eZ Publishがインストールされているディレクトリ直下の extensionディレクトリに jacextensionという名前のディレクトリを新規作成し、その後、下記のようなディレクトリや PHPファイルを作成しましょう。

ez/ |-- extension/ | |-- jacextension/ | | |-- modules/ | | | |-- modul1/ | | | | |-- list.php | | | | |-- module.php | | |-- settings/ | | | |-- module.ini.append.php

Page 5: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

module.ini.append.phpという名前のコンフィグファイルで jacextensionでのモジュールを見つけるよう eZ Publishに命じます。このことにより、eZ Publishは extension/jacextension/modules/に設置されたモジュール(modul1のような)を読み込みます。

ヒント : INIファイルでは行の最後に空白(スペース)を付けてはなりません!付けると正しく動作しないことがあります!

<?php/* #?ini charset="utf-8"? # tell ez publish to search after modules in the extension jacextension [ModuleSettings] ExtensionRepositories[]=jacextension # For eZ Publish 4.1 and up you'll need to specify your module name as well ModuleList[]=modul1 */ ?>

例 1: モジュール設定ファイル:extension/jacextension/settings/module.ini.append.php

Page 6: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

extensionの初期知識

ビューリスト

モジュールのビューは module.phpというファイルで定義します。モジュールのビューを利用することにより PHPファイルへのアクセスが可能となります。このサンプルでは$ViewList['list']によりビューの名前を定義でき、list.phpというカスタム PHPスクリプトにアクセスさせることができます。

また、ここではビューにいくつかのパラメーターを渡します。例えば、ParamOneと ParamTwoという 2つのパラメータを定義する場合は下記のように記載します。

'params' => array('ParamOne','ParamTwo')

下記は module.phpでの例です。

<?php // Introduction in the development of eZ Publish extensions $Module = array( 'name' => 'Example Modul1' ); $ViewList = array(); // new View list with 2 fixed parameters and // 2 parameters in order // http://.../modul1/list/ $Params['ParamOne'] / // $Params['ParamTwo']/ param4/$Params['4Param'] /param3/$Params['3Param'] $ViewList['list'] = array( 'script' => 'list.php', 'functions' => array( 'read' ), 'params' => array('ParamOne', 'ParamTwo'), 'unordered_params' => array('param3' => '3Param', 'param4' => '4Param') ); // The entries in the user rights // are used in the View definition, to assign rights to own View functions // in the user roles $FunctionList = array(); $FunctionList['read'] = array(); ?>

例 2 ビューのコンフィグ: extension/jacextension/modules/modul1/module.php

このモジュール用の URL:

http://localhost/ez/index.php/plain_site/modul1/list/<ValueParamOne>/<ValueParamTwo>

上記 URLを経由して下記のように list.phpで記述した変数にアクセスできます。

$valueParamOne = $Params['ParamOne']; $valueParamTwo = $Params['ParamTwo'];

上記のようなパラメータアクセスを順番付け有りパラメータ(オーダード・パラメーター)と呼びます。

Page 7: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

順番付け無しパラメータ(アンオーダード・パラメーター)は順番付け有りパラメータとは違い、名前と値のペアで構成されます。例えば下記のようになります。

http://localhost/ez/index.php/plain_site/modul1/list/ValueParamOne/ValueParamTwo/(param3)/ValueParam3/(param4)/ValueParam4

順番付け無しパラメータは順番付け有りパラメータと同様、module.phpで下記のように定義します。

'unordered_params' => array('param3' => '3Param', 'param4' => '4Param' )

上記により、URL上の param4が、PHPビュー上の 4paramというパラメータとしてマッチします。

例えば、URL上に.../param4/141とあった場合、eZ Publishはパラメータ param4に 141が代入され、その結果下記のようにその値を取得できます。

$Params['4Param']

順番付け無しパラメータはその名の通り順番に依存しません。順番付け無しパラメータが URL上にない場合、値には falseがセットされます。順番付け有りパラメータは値を持つべきですが、ない場合、値には NULLが代入されます。

http://localhost/ez/index.php/plain_site/modul1/list/table/5/(param4)/141/(param3)/131

といった URLではパラメータとして下記のように代入されていることになります。

$Params['ParamOne'] = 'table'; $Params['ParamTwo'] = '5'; $Params['3Param'] = '131'; $Params['4Param'] = '141';

詳細については下記 eZ Publishドキュメントを参照してください。

http://doc.ez.no/eZ-Publish/Technical-manual/4.x/Concepts-and-basics/Modules-and-views

一般的な慣習として URL上のビュー名とその関連 PHPファイル名は同じものを使います。このことでURLからどの PHPファイルが読み込まれているかがわかります。例えば、下記 URLをみてください。

http://localhost/ez/index.php/plain_site/content/view/full/2

上記では kernelモジュール contentの view.phpにアクセスします(<ezroot>/kernel/content/view.php)。

ヒント : eZ Publishの kernelモジュールは eZ Publishを勉強するプログラマーにとって最良のサンプルコードといえるかもしれません。kernelモジュールの構造は extensionの構造(例えば今回の modul1の構造も)と一緒です。

Page 8: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

ここでスクリーン上でビューリストの呼び出しを表示させるために、list.php内で echoコマンドを追加します。

<?php // take current object of type eZModule $Module = $Params['Module']; // read parameter Ordered View // http://.../modul1/list/ $Params['ParamOne'] / $Params['ParamTwo'] // for example .../modul1/list/view/5 $valueParamOne = $Params['ParamOne']; $valueParamTwo = $Params['ParamTwo']; // read parameter UnOrdered View // http://.../modul1/list/(param4)/$Params['4Param']/(param3)/$Params['3Param'] // for example.../modul1/list/.../.../(param4)/141/(param3)/131 $valueParam3 = $Params['3Param']; $valueParam4 = $Params['4Param']; // show values of the View parameter echo 'Example: modul1/list/'. $valueParamOne .'/ '. $valueParamTwo .'/(param4)/'. $valueParam4 .'/(param3)/'. $valueParam3; ?>

例 3. ビューリストの Functionファイル: extension/jacextension/modules/modul1/list.php

Page 9: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

extensionの有効化

jacextensionのモジュール modul1のビューリストをテストするには、extensionを有効化する必要があります。有効化にはグローバルな site.ini.append.php(例 4)か、特定のサイトアクセスのためのsite.ini.append.php(例 5)を利用します。グローバルな設定で extensionを有効にする場合はActiveExtensions[]で設定し有効化します。特定のサイトアクセスで有効にする場合はActiveAccessExtensions[]で設定し有効化します。

<?php /* #?ini charset="utf-8"? [ExtensionSettings] ActiveExtensions[] ActiveExtensions[]=jacextension ... */ ?>

例 4. オプション 1 - グローバルなコンフィグファイル上ですべてのサイトアクセスに対して extensionを有効にします:settings/override/site.ini.append.php

<?php /* #?ini charset="utf-8"? ... [ExtensionSettings] ActiveAccessExtensions[]=jacextension ... */ ?>

例 5. オプション 2 - 特定のサイトアクセス向けのコンフィグファイル上で extensionを有効にします:settings/siteaccess/plain_site/site.ini.append.php

権限管理システム

modul1のビューリストを開くための URLを叩いてみましょう。

http://localhost/ez/index.php/plain_site/modul1/list/table/5/(param4)/141

eZ Publishは「access denied」の文字列を返します。なぜでしょう?それは匿名ユーザー(Anonymous user)に modul1を利用する権限がないからです。

権限を与えるには2つの方法があります。まずその一つの方法として、設定ファイル extension/jacextension/settings/site.ini.append.php に PolicyOmitList[]=modul1/list の記述を行うことで全てのユーザーに利用権限を付与できます。(例 6)

<?php /* #?ini charset="utf-8"? [RoleSettings] PolicyOmitList[]=modul1/list */ ?>

例6. 設定ファイル extension/jacextension/settings/site.ini.append.php でmodul1のビューリストを全ユーザーに利用権限を付与。

あともう一つは、eZ Publishの管理画面からユーザーのアクセス権限を変更する方法です。管理画面で匿名ユーザー(Anonymous User)のロールにモジュール modul1の functionにアクセス権限を与えましょう。URL: http://localhost/ez/index.php/plain_site_admin/role/view/1 にアクセスしてみてください。

Page 10: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

extensionモジュールの module.php上の配列$FunctionListにおいて functionを定義します。配列のキーとして functionを記述します。この例では user functionの readとしてビューリストにリンクしましょう。

$FunctionList['read'] = array(); // with 'functions' => array( 'read' ) in the $ViewList array

配列$FunctionListを使って、特定の user functionとモジュールのビューをリンクさせます。user functionには「create」もあり、すべてのビューでコンテンツ作成ができるような権限を付与することもできます。今回は編集者にのみ create権限を利用可能にします。

また、「read」(読む)functionについては匿名ユーザー(Anonymous user)を含め、すべてのユーザーに許可を与えます。

権限設定についてより詳しく知りたい方は、チュートリアル「Adding custom security policy limitations to your modules」をチェックしてください。

Page 11: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

テンプレート・システム

さて、list.php上の echo commandでの表示では力不足で要件に合わず、テンプレートを使って情報を表示したくなったとします。その要件を満たすためには、jacextension/design/standard/templates/modul1/に list.tplを作成します。

テンプレート利用するためには、jacextensionが design extensionであることを宣言することが必須です。そのため、フォルダ jacextension/settings/にコンフィグファイル design.ini.append.phpを作成します。(例 7)

<?php /* #?ini charset="utf-8"? # transmit to eZ, to search for designs in jacextension [ExtensionSettings] DesignExtensions[]=jacextension */ ?>

例 7. jacextensionを design extensionとして宣言

その後、list.phpで配列$dataArray(文字列の配列)を宣言します。この配列の値はテンプレート list.tplで利用します。テンプレート list.tplを利用するため、まずテンプレートオブジェクトを初期化しなければなりません。

$tpl = eZTemplate::factory(); // Notation from eZP 4.3. Before this version, use templateInit() function

それからビュー上の URLから取得できるパラメータ配列 ($viewParameters)と予め php上で定義する配列 ($dataArray) を、テンプレート変数として{$view_parameters}や{$data_array}といった形で利用できるように下記記述を行います。

$tpl->setVariable( 'view_parameters', $viewParameters ); $tpl->setVariable( 'data_array', $dataArray );

次にテンプレート list.tpl上で適当に定義したテンプレート変数(この例では$view_parametersと$data_arrayしかないですが)を組み込みます。そして、$Result['content']に上記結果を格納します。

デフォルトでは、eZ Publishのメインテンプレート pagelayout.tpl において {$module_result.content}という変数で上記結果を呼び出すことができます。(例 8)

<?php // Example array with strings $dataArray = array( 'Axel','Volker','Dirk','Jan','Felix' ); ... // initialize Templateobject $tpl = eZTemplate::factory(); // create view array parameter to put in the template $viewParameters = array( 'param_one' => $valueParamOne, 'param_two' => $valueParamTwo, 'unordered_param3' => $valueParam3, 'unordered_param4' => $valueParam4 ); // transport the View parameter Array to the template $tpl->setVariable( 'view_parameters', $viewParameters ); // create example Array in the template => {$data_array} $tpl->setVariable( 'data_array', $dataArray );

Page 12: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

// ... // use find/replace (parsing) in the template and save the result for $module_result.content $Result['content'] = $tpl->fetch( 'design:modul1/list.tpl' ); //... ?>

例 8. modul1/list.php - 例 3の拡張

以上の設定/定義により {$view_parameters} と {$data_array} をテンプレート list.tpl上で呼び出すことができるようになりました。{$view_parameters|attribute(show)}という記述をテンプレートに書けば$view_parametersの内容を表示できます。また、テンプレート・オペレータ is_set($data_array)により変数$data_arrayが存在するかを確認する記述をしてみましょう。例 9ではデータがセットされていればデータが一覧表示され、セットされていなければ「Attention: no existing data!!」と表示されるように記述しています。

{* list.tpl – Template for Modulview .../modul1/list/ParamOne/ParamTwo Check if the variable $data_array exists - yes: show data as list - no: show message *} {*Show Array $view_parameters: *} {$view_parameters|attribute('show')}<br /> <h1>Template: modul1/list.tpl</h1> {if is_set($data_array)} <ul> {foreach $data_array as $index => $item} <li>{$index}: {$item}</li> {/foreach} </ul> {else} <p>Attention: no existing data!!</p> {/if}

例 9. eZ テンプレート・デザイン modul1/list.tpl(extension/jacextension/design/<your_design>templates/modul1/list.tpl)

さて、http://localhost/ez/index.php/plain_site/modul1/list/table/5 を再度開いてみても前と変化がない場合があります。なぜでしょう? 答えは画面にも書いてありません。

そんな時、エラーの原因を調べたい場合は eZ Debugを有効化しましょう。また、テンプレートの変化をスムーズにチェックできるようにするため、テンプレートのキャッシュ機能は無効にしましょう。グローバルな設定 <ezroot>/settings/override/site.ini.append.phpを例 10のように修正します。

Page 13: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

<?php /* #?ini charset="utf-8"? [DebugSettings] Debug=inline DebugOutput=enabled DebugRedirection=disabled [TemplateSettings] ShowXHTMLCode=disabled ShowUsedTemplates=enabled TemplateCompile=disabled TemplateCache=disabled # Optional, will save you from most cache clearings during development # as modified time on tempaltes are always checked during execution DevelopmentMode=enabled */?>

例 10. グローバルコンフィグファイルでテンプレートでの Debugを有効化: ezroot/settings/override/site.ini.append.php

上記設定の後、再度 http://localhost/ez/index.php/plain_site/modul1/list/table/5にアクセスしてみましょう。するとこんな Debugメッセージが表示されることがあります。

'No template could be loaded for "modul1/list.tpl" using resource "design"' (modul1/list.tplとしてロードされるはずのテンプレートが見つかりません)

どうやら list.tplが見当たらないと eZ Publishがいっています。こういった場合は、それまでのテンプレートの状態をキャッシュしている可能性が高いので、まず eZ Publishのキャッシュをクリアしましょう。 http://localhost/ez/index.php/plain_site_admin/setup/cacheにアクセスして「全てのキャッシュをクリア」をクリックします。キャッシュをクリアしたら list.tplは table listや view_parameters、そして、サンプルのデータリストを表示するはずです。同様に Debug情報も表示されていることでしょう。

この例では、ビューパラメータは下記のような値を持っています。

$view_parameters.param_one='table' $view_parameters.param_two='5'

ビューパラメータの値は PHPスクリプト list.phpやテンプレート list.tplでのアクションに利用できます。(例えば、IDの表示やその IDから値を引き出したりすることができます)

ヒント:テンプレート変数$view_parametersは eZの kernelモジュールにおいても有効なため、node/view/full.tplといったほとんどのテンプレートで利用できます。

Page 14: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

ビューの作成

さて次に新しいビューを作成してこのサンプルをもっと拡張しましょう。データベース上に配列データを保存できるように「jacextension_data」と名づけた新しいデータベース・テーブルを用意します。このテーブルは例 11のように id | user_id | created | valueの4つのカラムを持たせることにします。

CREATE TABLE jacextension_data ( id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , user_id INT( 11 ) NOT NULL , created INT( 11 ) NOT NULL , value VARCHAR( 50 ) NOT NULL ) ENGINE = MYISAM ;

例 11. jacextension_dataという新規テーブルを作成するための SQL文

次に list.phpを create.php、list.tplを create.tplとしてコピーします。そして、新しいビューや create.phpとリンクするロール function ("create")が利用できるように module.phpを拡張します。それからdesign:modul1/create.tplを呼び出せるように create.tplのテンプレート・コールを変更し、かつ、ビュー modul1/createの権限を調整します。以上が終わったら最後にキャッシュをクリアしましょう。

これで URL http://localhost/ez/index.php/plain_site/modul1/create が動作するためのお膳立てができました。しかし、いまのところその URLにアクセスしてもビューパラメータを省略した modul1/listと同じ見た目となるでしょう。

MySQLデータベースにデータを保存するには、ビューにおいて POSTや GETを利用してデータを送信するための HTMLフォームが必要です。ですので、テンプレート create.tplにフォームの記述を行います。この例では GETを利用してデータを送信させましょう。また、テンプレート変数{$status_message}を新規に用意してユーザーの入力メッセージを表示させましょう。(例 12を見てください)

{* create.tpl – template for Modulview .../modul1/create Html form to save the new data *} <form action={'modul1/create'|ezurl} method="get"> Name :<br /> <input name="name" type="text" size="50" maxlength="50"><br /> <input type="submit" name="DataCreation" value="Create new data"> <input type="reset" value="Cancel"> </form> <hr> Status: {$status_message}

例 12. データを保存するためのフォームを持つテンプレート jacextension/design/standard/templates/modul1/create.tpl

GET / POST

以上により、パラメータ nameの GET値を表示できるように list.phpを変更し、その値は PHPスクリプトに送信されます。その後、テンプレートの statusフィールドにその値が表示されます。GET値やPOST値を表示するには eZ Publishフレームワークの eZHTTPToolクラスを利用します。

まず$http = eZHTTPTool::instance()により eZHTTPToolのオブジェクトを参照します。

$http->hasVariable('name')により$_GET['name'] や $_POST['name']が存在するかどうかチェックできます。そして、$http->variable('name')によりその値を取得できます。もし GET値だけ、とか、POST値だけ取得したい場合は$http->hasGetVariable('name'); や $http->hasPostVariable('name'); を利用します。

Page 15: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

その他の function(例えばセッション関連)の情報は eZ Publishの APIドキュメントに記述されています。eZHTTPTool classについては http://pubsvn.ez.no/doxygen/4.4/html/classeZHTTPTool.html を見てください。

ログを出力したいなら、eZLog::write()を利用します。デフォルトのログも様々な情報を出力していますが、デフォルトのログは見づらいのでオリジナルのログ出力が便利な場合もあるでしょう。

<?php // modul1/create.php – Function file of View create $Module = $Params['Module']; // take copy of global object $http = eZHTTPTool::instance (); $value = ''; // If the variable 'name' is sent by GET or POST, show variable if( $http->hasVariable('name') ) $value = $http->variable ('name'); if( $value != '' ) $statusMessage = 'Name: '. $value; else $statusMessage = 'Please insert data'; // initialize Templateobject $tpl = eZTemplate::factory(); // From eZPublish 4.3. For previous versions, use templateInit() function instead $tpl->setVariable( 'status_message', $statusMessage ); // Write variable $statusMessage in the file eZ Debug Output / Log // here the 4 different types: Notice, Debug, Warning, Error eZDebug::writeNotice( $statusMessage, 'jacextension:modul1/list.php' ); eZDebug::writeDebug( $statusMessage, 'jacextension:modul1/list.php' ); eZDebug::writeWarning( $statusMessage, 'jacextension:modul1/list.php' ); eZDebug::writeError( $statusMessage, 'jacextension:modul1/list.php' ); // $statusMessage write own Log file to ezroot/var/log/jacextension_modul1.log eZLog::write ( $statusMessage, 'jacextension_modul1.log' ); $Result = array(); // search/replace template and save result for $module_result.content $Result['content'] = $tpl->fetch( 'design:modul1/create.tpl' ); // generate route Modul1/create $Result['path'] = array( array( 'url' => 'modul1/list', 'text' => 'Modul1'), array( 'url' => false, 'text' => 'create' ) ); ?>

例 13. GET/POST値の表示、および、Debugメッセージの出力の実現: jacextension/module/modul1/create.php

Page 16: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

データベースへのアクセス

さて、データベースに戻りましょう。新しく作った jacextension_dataテーブルにフォームの値を保存してみます。そのために必要なクラスは eZPersistentObjectです。このクラスはデータの作成、変更、削除や抽出といった機能を持っています。

これらの機能を使うに、まずは JACExtensionDataというクラスを newして作りましょう。このクラスは jacextensiondata.phpという名前で<ezroot>/extension/jacextension/classesに保存します。

<?php class JACExtensionData extends eZPersistentObject { /** * Constructor * * @param array $row Hash of attributes for new JacExtensionData object */ public function __construct( array $row ) { parent::eZPersistentObject( $row ); } /* * Definition of the data object structure /of the structure of the database table * * @return array Hash with table definition for this persistent object */ public static function definition() { return array( 'fields' => array( 'id' => array( 'name' => 'ID', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'user_id' => array( 'name' => 'UserID', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'created' => array( 'name' => 'Created', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'value' => array( 'name' => 'Value', 'datatype' => 'string', 'default' => '', 'required' => true ) ), 'keys'=> array( 'id' ), 'function_attributes' => array( 'user_object' => 'getUserObject' ), // accessing to attribute "user_object" will trigger getUserObject() method 'increment_key' => 'id', 'class_name' => 'JACExtensionData', 'name' => 'jacextension_data' ); } /** * Help function will open in attribute function * @param bool $asObject */ public function getUserObject( $asObject = true ) { $userID = $this->attribute('user_id');

Page 17: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

$user = eZUser::fetch($userID, $asObject); return $user; } /** * Creates a new object of type JACExtensionData and shows it * @param int $user_id * @param string $value * @return JACExtensionData */ public static function create( $user_id, $value ) { $row = array( 'id' => null, 'user_id' => $user_id, 'value' => $value, 'created' => time() ); return new self( $row ); } /** * Shows the data as JACExtensionData with given id * @param int $id User ID * @param bool $asObject * @return JACExtensionData */ public static function fetchByID( $id , $asObject = true) { $result = eZPersistentObject::fetchObject( self::definition(), null, array( 'id' => $id ), $asObject, null, null ); if ( $result instanceof JACExtensionData ) return $result; else return false; } /** * Shows all the objects JACExtensionData as object or array * @param int $asObject * @return array( JACExtensionData ) */ public static function fetchList( $asObject = true ) { $result = eZPersistentObject::fetchObjectList( self::definition(), null,null,null,null, $asObject, false,null ); return $result; } /** * Shows the amount of data * @return int */ public static function getListCount() { $db = eZDB::instance(); $query = 'SELECT COUNT(id) AS count FROM jacextension_data'; $rows = $db -> arrayQuery( $query ); return $rows[0]['count']; } // -- member variables--

Page 18: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

protected $ID; protected $UserID; protected $Created; protected $Value; } ?>

例 14. eZ PersistentObjectによるデータベースアクセスの例: jacextension/classes/jacextensiondata.php

特に重要なメソッドは JACExtensionData::definition()です。このメソッドは JACExtensionDataのオブジェクト構造を定義し、データが保存されるテーブル/カラムの仕様を特定します。

次に create(), fetchByID(), fetchList(), getListCount()という静的メソッドを作成します。データが表示については3つのタイプがあります。

1. eZPersistentObject::fetchObject() 2. eZPersistentObject::fetchObjectList() 3. direct SQL command

可能な限り、eZPersistentObjectの fetchメソッドを利用しましょう。eZ Publishが対応しているデータベース上での SQLは動作しますが、特定のデータベース依存な SQLを利用すべきではないでしょう。(より詳細は関連 APIドキュメントのhttp://pubsvn.ez.no/doxygen/4.4/html/classeZPersistentObject.html を参照してください)

この新しいクラスを利用する前に、autoloads配列を再発行する必要があります。このオペレーションにより eZ Publishがシステム上で必要な PHPクラスを見つけることができるようになります。

cd /path/to/ezpublish/root php bin/php/ezpgenerateautoloads.php -e -p

これで create.phpの新しい機能を使うことができます。新規データ保存を行うにあたりメソッドJACExtensionData::create( $value )により JACExtensionData型の新規オブジェクトを作成できます。メソッド create()はフォームに入力された値とユーザーID、そして入力した時刻を作成します。

メソッド store()により、jacextension_dataテーブルにデータが保存されます。この時生じていることは Debug Viewで知ることができます。create.phpは下記のようになります。

<?php // modul1/create.php – Function file of View create // ... $value = ''; // If the variable 'name' is sent by GET or POST, show variable if( $http->hasVariable('name') ) $value = $http->variable('name'); if( $value != '' ) { // ask for the ID of current user $userId = eZUser::currentUserID(); // generate new data object $JacDataObject = JACExtensionData::create( $userId, $value ); eZDebug::writeDebug( '1.'.print_r( $JacDataObject, true ), 'JacDataObject before saving: ID not set' ) ;

Page 19: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

// save object in database $JacDataObject->store(); eZDebug::writeDebug( '2.'.print_r( $JacDataObject, true ), 'JacDataObject after saving: ID set' ) ; // ask for the ID of the new created object $id = $JacDataObject->attribute( 'id' ); // ask for the login of the user who has created the data $userObject = $JacDataObject->attribute( 'user_object' ); $userName = $userObject->attribute( 'login' ); // show again the data $dataObject = JACExtensionData::fetchByID( $id ); eZDebug::writeDebug( '3.'.print_r( $dataObject, true ), 'JacDataObject shown with function fetchByID()'); // investigate the amount of data existing $count = JACExtensionData::getListCount(); $statusMessage = 'Name: >>'. $value . '<< of the user >>'. $userName. '<< In database with ID >>'. $id. '<< saved!New ammount = '. $count ; } else { $statusMessage = 'Please enter data'; } // take data as object and as array and show in Output Debug $ObjectArray = JACExtensionData::fetchList( true ); eZDebug::writeDebug( '4. JacDataObjects: '.print_r( $ObjectArray, true ), 'fetchList( $asObject = true )' ); $array = JACExtensionData::fetchList( false ); eZDebug::writeDebug( '5. JacDataArrays: '.print_r( $array, true ), 'fetchList( $asObject = false )' ); // initialize Templateobject $tpl = eZTemplate::factory(); $tpl->setVariable( 'status_message', $statusMessage ); //... ?>

例 15. データベースへの新規書き込みと、そのデータを違ったやり方で表示しています。: jacextension/modules/modul1/create.php

eZPersistentObject型のオブジェクトにアクセスするには、$JacDataObject- >attribute('id')を使います。パラメータ「id」はテーブルの idカラムに適合しており、その他の値についてアクセスについて深く考える必要はありません。このことは eZ Publishに保存されるすべてのデータについていえることです。(例えば、eZContentObjectや eZUserといったオブジェクトも同様)

Page 20: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

テンプレート・フェッチ機能

注意:カスタム・フェッチ機能の作成については Understanding and developing fetch functionsがより詳しいです。

ここまででパラメータや GET値や POST値を新しいビューに表示させる方法を書いてきました。しかし、データベースに格納されたデータを eZ Publishのテンプレートに表示したい場合、ビューのみでハンドリングすることができません。

データを取得するには、eZの kernelモジュールの機能である fetchを利用します。(例:{fetch('content', 'node', hash( 'node_id', 2 )}) ここでは listと countという2つの fetch機能を定義したいと思います。テンプレート上での記述の方法は次のとおりです。

{fetch( 'modul1', 'list', hash( 'as_object' , true() ) )} {fetch( 'modul1', 'count', hash() )}

list機能は配列やオブジェクト('as_object'のパラメータがセットされた場合)としてデータを表示します。count機能はパラメータを持ちませんが、テーブル jacextension_data 内のデータの合計数を集計する SQLコマンドを使います。

fetch機能の定義は jacextension/modules/modul1/function_definition.phpで行います。この PHPファイルではどのパラメータがどのメソッドに送信するかについても定義します。

<?php $FunctionList = array(); // {fetch('modul1','list', hash('as_object', true()))|attribute(show)} $FunctionList['list'] = array( 'name' => 'list', 'operation_types' => array( 'read' ), 'call_method' => array( 'class' => 'eZModul1FunctionCollection', 'method' => 'fetchJacExtensionDataList' ), 'parameter_type' => 'standard', 'parameters' => array( array( 'name' => 'as_object', 'type' => 'integer', 'required' => true ) ) ); //{fetch('modul1','count', hash())} $FunctionList['count'] = array( 'name' => 'count', 'operation_types' => array( 'read' ), 'call_method' => array( 'class' => 'eZModul1FunctionCollection', 'method' => 'fetchJacExtensionDataListCount' ), 'parameter_type' => 'standard', 'parameters' => array() ); ?>

例 16. modul1の fetch機能の定義: extension/jacextension/modules/modul1/function_defintion.php

jacextension/modules/modul1/ezmodul1functioncollection.phpはすべての fetch機能に対応するヘルプクラスです。

Page 21: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

<?php class eZModul1FunctionCollection { public function __construct() { // ... } /* * Is opened by('modul1', 'list', hash('as_object', $bool ) ) fetch * @param bool $asObject */ public static function fetchJacExtensionDataList( $asObject ) { return array( 'result' => JACExtensionData::fetchList( $asObject ) ); } /* * Is opened by('modul1', 'count', hash() ) fetch */ public static function fetchJacExtensionDataListCount() { return array( 'result' => JACExtensionData::getListCount() ); } } ?>

例 17. function_defintion.phpで定義された fetch機能で利用可能なヘルプクラス: extension/jacextension/modules/modul1/ezmodul1functioncollection.php

ヒント:どのモジュールでも、functioncollection.phpでは fetch機能の hash()に利用可能なパラメータの一覧が格納されます。eZ Publishの kernel contentモジュールにおいて{fetch('content', 'tree', hash( ... ) )}のような fetch機能がどんなパラメータを利用可能か知りたいのならば、kernel/content/ezcontentfunctioncollection.phpを調べてみてください。

eZ Publishのドキュメントが不十分な場合はとても参考になるはずです。

繰り返しになりますが、PHPクラスを新しく作ったら、忘れずに autoloadの再発行をしてください。

Page 22: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

テンプレート・オペレータ

extensionの機能にアクセスする別の方法はテンプレート・オペレータを利用することです。eZ Publishは多くのテンプレート・オペレータを持っていますが、今回は新規に$result_type パラメータを呼び出すテンプレート・オペレータを定義してみましょう。

このパラメータはデータベース・テーブル上のデータを表示します。テンプレート・コマンド{jac('list')}はデータの一覧を表示し、{jac('count')}はデータの総数を表示します。

テンプレート・フェッチでも同様な機能を次のように行えます。

fetch('modul1', 'list' , ...) and fetch( 'modul1', 'count', ... )

jacextensionのテンプレート・オペレータを eZ Publishにロードさせる記述はextension/jacextension/autoloads/eztemplateautoload.phpで行います。(例 18) テンプレート・オペレータの actionは extension/jacextension/autoloads/jacoperator.phpの JACOperator内でカスタム PHPクラスを定義します。(例 19)

<?php // Which operators will load automatically? $eZTemplateOperatorArray = array(); // Operator: jacdata $eZTemplateOperatorArray[] = array( 'class' => 'JACOperator', 'operator_names' => array( 'jac' ) ); ?> Listing 18. extension/jacextension/autoloads/eztemplateautoload.php <?php /** * Operator: jac('list') and jac('count') <br> * Count: {jac('count')} <br> * Liste: {jac('list')|attribute(show)} */ class JACOperator { public $Operators; public function __construct( $name = 'jac' ) { $this->Operators = array( $name ); } /** * Returns the template operators. * @return array */ function operatorList() { return $this->Operators; } /** * Returns true to tell the template engine that the parameter list * exists per operator type. */ public function namedParameterPerOperator() { return true; }

Page 23: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

/** * @see eZTemplateOperator::namedParameterList **/ public function namedParameterList() { return array( 'jac' => array( 'result_type' => array( 'type' => 'string', 'required' => true, 'default' => 'list' )) ); } /** * Depending of the parameters that have been transmitted, fetch objects JACExtensionData * {jac('list)} or count data {jac('count')} */ public function modify( $tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters ) { $result_type = $namedParameters['result_type']; if( $result_type == 'list') $operatorValue = JACExtensionData::fetchList(true); else if( $result_type == 'count') $operatorValue = JACExtensionData::getListCount(); } } ?>

例 19. extension/jacextension/autoloads/jacoperator.php

繰り返しになりますが、PHPクラスを新しく作ったら、忘れずに autoloadの再発行をしてくださいね :)

jacextensionにテンプレート・オペレータが含まれていることを eZ Publishに知らせるために、eZ Publishのコンフィグファイル extension/jacextension/settings/site.ini.append.phpでExtensionAutoloadPath[]=jacextensionの記述を行います。(例 20)

<?php /* #?ini charset="utf-8"? ... # search for template operators in jacextension [TemplateSettings] ExtensionAutoloadPath[]=jacextension */ ?>

例 20. extension/jacextension/settings/site.ini.append.php

テンプレート・オペレータ jac('list') や jac('count')の template fetch機能の fetch('modul1', 'list', hash('as_object', true() ) ) と fetch( 'modul1', 'count', hash() ) をテストするために、ビューリストのテンプレート list.tplを拡張します。(例 21)

<h2>Template Operator: jac('count') and jac('list')</h2> Count: {jac( 'count' )} <br /> List: {jac( 'list' )|attribute( 'show' )} <hr /> <h2>Template Fetch Functions: fetch( 'modul1','count', hash() )<br /><br /> fetch( 'modul1','list', hash( 'as_object', true() ) )</h2> Count: {fetch( 'modul1', 'count', hash() )} <br> List: {fetch( 'modul1', 'list', hash( 'as_object', true() ) )|attribute( 'show' )}

例 21. カスタム・テンプレート・フェッチ機能とテンプレート・オペレータのテスト - extension/jacextension/design/standard/templates/modul1/list.tpl

ビューを開いてみましょう。例えば、http://localhost/ez/index.php/plain_site/modul1/list/tableblue/1234

すると、例として作った$data_arrayに格納された値とは別に、テーブル jacextension_data 上のデー

Page 24: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

タが 2度表示されることでしょう。一つはテンプレート・オペレータによるもの、もう一つはテンプレート・フェッチ機能によるものです。このことからもわかるように、テンプレートにおける値呼び出しについては様々なやり方が可能です。

Page 25: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

INIファイル

最後に extension/jacextension/settings/jacextension.ini.というオリジナルの設定ファイルを作りましょう。この設定はテンプレートやモジュールについて必要な設定値であり、他の eZ Publishインストールにおいて変更されることもあるでしょう。

デフォルトの.iniは jacextension.ini.append.phpに上書きされます。例 22では.iniファイルの例を、例23では list.phpを変更して PHPから.iniファイルにアクセスするコードを書いています。

[JACExtensionSettings] # Should Debug enabled / disabled JacDebug=enabled

例 22. jacextensionのコンフィグファイル - extension/jacextension/settings/jacextension.ini

<?php // ... // read variable JacDebug of INI block [JACExtensionSettings] // of INI file jacextension.ini $jacextensionINI = eZINI::instance( 'jacextension.ini' ); $jacDebug = $jacextensionINI->variable( 'JACExtensionSettings','JacDebug' ); // If Debug is activated do something if( $jacDebug === 'enabled' ) echo 'jacextension.ini: [JACExtensionSetting] JacDebug=enabled'; // ... ?>

例 23. jacextension.iniへのアクセス - extension/jacextension/modules/modul1/list.php

Page 26: eZ Publishのextension開発チュートリアル

eZ  Publishの extension開発  チュートリアル  (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  

最後に

この簡単なサンプルにより、eZ Publish extensionの作成についてのテクニックをいくつか学びました。

オリジナルのビューやビューパラメータ、テンプレート・フェッチ機能やテンプレート・オペレータをカスタムモジュールで実現することに加え、eZ Publishの権限管理システムについてふれ、また、デバッグビューやログファイルにカスタムメッセージを表示するやり方も扱いました。そして iniファイルへのアクセスについても。

これらの基本的な知識を利用して、きっと eZ Publish extensionの作成が可能になったかと思います。

このチュートリアルで作ったサンプルコードは http://projects.ez.no/jacextensionからダウンロードすることができます。

Resources

http://www.ezpublish.de/ – German eZ community

http://share.ez.no - International eZ community

http://pubsvn.ez.no/doxygen – eZ API documentation

http://doc.ez.no/eZ-Publish/Technical-manual/4.x/Reference – eZ reference documentation

http://projects.ez.no/jac_dokumentation_in_german_ez_publish_basics_extension_development – PDF eZ publish basics in programming modules (in German)

http://projects.ez.no/index.php/jac_tutorial_ger_de_ez_publish_extension_entwicklung - This tutorial in German (not refreshed to be 4.4 compliant yet)

http://projects.ez.no/index.php/jac_tutorial_esl_es_desarrollo_de_extensiones_en_ez_publish - This tutorial in Spanish (not refreshed to be 4.4 compliant yet)

http://projects.ez.no/jacextension - Source code for the tutorial