SlideShare a Scribd company logo
1 of 26
Download to read offline
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 要件に

                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 フレームワ
ークでどう開発を行うか?をお見せします。




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

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

extension を作成すると eZ Publish の機能追加、または既存機能の拡張を行うことができます。extension
を利用により eZ Publish の本体ファイルを変更することなく、 Publish のコア機能を拡張することが
                                         eZ
できます。そのため、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/も利用する
場合があります。




                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




           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




          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'];



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




           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
の構造も)と一緒です。




           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




          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 にアクセスしてみてください。




           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 権限を利用可能にします。

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

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




          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 );

          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 のように修正します。




           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 といったほとんどのテンプレートで利用できます。




          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'); を利用し
ます。




         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




          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');

         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--

     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' ) ;


          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 といったオブジェクトも同様)




            eZ	
  Publish の extension 開発	
   チュートリアル	
   (原著:	
  An	
  Introduction	
  to	
  Developing	
  eZ	
  Publish	
  Extensions)	
  
テンプレート・フェッチ機能

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

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

データを取得するには、 の kernel モジュールの機能である fetch を利用します。
                          eZ                                       (例:{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 機能に対応するヘルプ
クラスです。
           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 の再発行をしてください。




          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;
    }

         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 上のデー
            eZ	
  Publish の extension 開発	
   チュートリアル	
   (原著:	
  An	
  Introduction	
  to	
  Developing	
  eZ	
  Publish	
  Extensions)	
  
タが 2 度表示されることでしょう。一つはテンプレート・オペレータによるもの、もう一つはテンプレ
ート・フェッチ機能によるものです。このことからもわかるように、テンプレートにおける値呼び出し
については様々なやり方が可能です。




     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




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

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

オリジナルのビューやビューパラメータ、テンプレート・フェッチ機能やテンプレート・オペレータを
カスタムモジュールで実現することに加え、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




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

More Related Content

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

eZ Publish勉強会2013年3月「eZ Publishの構築を簡単に!」
eZ Publish勉強会2013年3月「eZ Publishの構築を簡単に!」eZ Publish勉強会2013年3月「eZ Publishの構築を簡単に!」
eZ Publish勉強会2013年3月「eZ Publishの構築を簡単に!」ericsagnes
 
2006 07 29_xtc2006_x_cube_template
2006 07 29_xtc2006_x_cube_template2006 07 29_xtc2006_x_cube_template
2006 07 29_xtc2006_x_cube_templateTom Hayakawa
 
Aeolus Conductorによる複数環境へのデプロイ自動化
Aeolus Conductorによる複数環境へのデプロイ自動化Aeolus Conductorによる複数環境へのデプロイ自動化
Aeolus Conductorによる複数環境へのデプロイ自動化Etsuji Nakai
 
Eclipse を使った java 開発 111126 杉浦
Eclipse を使った java 開発 111126 杉浦Eclipse を使った java 開発 111126 杉浦
Eclipse を使った java 開発 111126 杉浦urasandesu
 
PHP基礎勉強会
PHP基礎勉強会PHP基礎勉強会
PHP基礎勉強会Yuji Otani
 
Flash Builder4 と FlashCatalyst を使ってみた
Flash Builder4 と FlashCatalyst を使ってみたFlash Builder4 と FlashCatalyst を使ってみた
Flash Builder4 と FlashCatalyst を使ってみたguest0ba46c3
 
使いこなせて安全なLinuxを目指して
使いこなせて安全なLinuxを目指して使いこなせて安全なLinuxを目指して
使いこなせて安全なLinuxを目指してToshiharu Harada, Ph.D
 
20121115 fukuoka sublime0_kuroneko
20121115 fukuoka sublime0_kuroneko20121115 fukuoka sublime0_kuroneko
20121115 fukuoka sublime0_kuronekoKohki Nakashima
 
環境構築自動化ツールのご紹介
環境構築自動化ツールのご紹介環境構築自動化ツールのご紹介
環境構築自動化ツールのご紹介Etsuji Nakai
 
eZ Publish 2012年8月勉強会 - テンプレートオーバーライド
eZ Publish 2012年8月勉強会 - テンプレートオーバーライドeZ Publish 2012年8月勉強会 - テンプレートオーバーライド
eZ Publish 2012年8月勉強会 - テンプレートオーバーライドericsagnes
 
テキスト型Domain Specific Language (DSL) 開発フレームワークXtext の紹介
テキスト型Domain Specific Language (DSL) 開発フレームワークXtext の紹介テキスト型Domain Specific Language (DSL) 開発フレームワークXtext の紹介
テキスト型Domain Specific Language (DSL) 開発フレームワークXtext の紹介Shintaro Hosoai
 
10分でわかるFuelPHP @ 2011/12
10分でわかるFuelPHP @ 2011/1210分でわかるFuelPHP @ 2011/12
10分でわかるFuelPHP @ 2011/12kenjis
 
Personal Cloud Automation
Personal Cloud AutomationPersonal Cloud Automation
Personal Cloud AutomationEtsuji Nakai
 
2005 07 30_xwj_customizinig
2005 07 30_xwj_customizinig2005 07 30_xwj_customizinig
2005 07 30_xwj_customizinigTom Hayakawa
 

Similar to eZ Publishのextension開発チュートリアル (20)

eZ Publish勉強会2013年3月「eZ Publishの構築を簡単に!」
eZ Publish勉強会2013年3月「eZ Publishの構築を簡単に!」eZ Publish勉強会2013年3月「eZ Publishの構築を簡単に!」
eZ Publish勉強会2013年3月「eZ Publishの構築を簡単に!」
 
Ext.direct
Ext.directExt.direct
Ext.direct
 
2006 07 29_xtc2006_x_cube_template
2006 07 29_xtc2006_x_cube_template2006 07 29_xtc2006_x_cube_template
2006 07 29_xtc2006_x_cube_template
 
Aeolus Conductorによる複数環境へのデプロイ自動化
Aeolus Conductorによる複数環境へのデプロイ自動化Aeolus Conductorによる複数環境へのデプロイ自動化
Aeolus Conductorによる複数環境へのデプロイ自動化
 
Eclipse を使った java 開発 111126 杉浦
Eclipse を使った java 開発 111126 杉浦Eclipse を使った java 開発 111126 杉浦
Eclipse を使った java 開発 111126 杉浦
 
PHP基礎勉強会
PHP基礎勉強会PHP基礎勉強会
PHP基礎勉強会
 
PHP勉強会 #51
PHP勉強会 #51PHP勉強会 #51
PHP勉強会 #51
 
Flash Builder4 と FlashCatalyst を使ってみた
Flash Builder4 と FlashCatalyst を使ってみたFlash Builder4 と FlashCatalyst を使ってみた
Flash Builder4 と FlashCatalyst を使ってみた
 
Visual studio de debug
Visual studio de debugVisual studio de debug
Visual studio de debug
 
sveltekit-ja.pdf
sveltekit-ja.pdfsveltekit-ja.pdf
sveltekit-ja.pdf
 
使いこなせて安全なLinuxを目指して
使いこなせて安全なLinuxを目指して使いこなせて安全なLinuxを目指して
使いこなせて安全なLinuxを目指して
 
Boost Fusion Library
Boost Fusion LibraryBoost Fusion Library
Boost Fusion Library
 
20121115 fukuoka sublime0_kuroneko
20121115 fukuoka sublime0_kuroneko20121115 fukuoka sublime0_kuroneko
20121115 fukuoka sublime0_kuroneko
 
環境構築自動化ツールのご紹介
環境構築自動化ツールのご紹介環境構築自動化ツールのご紹介
環境構築自動化ツールのご紹介
 
eZ Publish 2012年8月勉強会 - テンプレートオーバーライド
eZ Publish 2012年8月勉強会 - テンプレートオーバーライドeZ Publish 2012年8月勉強会 - テンプレートオーバーライド
eZ Publish 2012年8月勉強会 - テンプレートオーバーライド
 
テキスト型Domain Specific Language (DSL) 開発フレームワークXtext の紹介
テキスト型Domain Specific Language (DSL) 開発フレームワークXtext の紹介テキスト型Domain Specific Language (DSL) 開発フレームワークXtext の紹介
テキスト型Domain Specific Language (DSL) 開発フレームワークXtext の紹介
 
10分でわかるFuelPHP @ 2011/12
10分でわかるFuelPHP @ 2011/1210分でわかるFuelPHP @ 2011/12
10分でわかるFuelPHP @ 2011/12
 
Personal Cloud Automation
Personal Cloud AutomationPersonal Cloud Automation
Personal Cloud Automation
 
2005 07 30_xwj_customizinig
2005 07 30_xwj_customizinig2005 07 30_xwj_customizinig
2005 07 30_xwj_customizinig
 
20050903
2005090320050903
20050903
 

More from 株式会社ミツエーリンクス

More from 株式会社ミツエーリンクス (7)

イマドキのCMSトレンドからWeb運用を再考する
イマドキのCMSトレンドからWeb運用を再考するイマドキのCMSトレンドからWeb運用を再考する
イマドキのCMSトレンドからWeb運用を再考する
 
これからのCMSマーケットトレンドとPHP (for fukuoka.php)
これからのCMSマーケットトレンドとPHP (for fukuoka.php)これからのCMSマーケットトレンドとPHP (for fukuoka.php)
これからのCMSマーケットトレンドとPHP (for fukuoka.php)
 
簡単なTYPO3エクステンションの作成
簡単なTYPO3エクステンションの作成簡単なTYPO3エクステンションの作成
簡単なTYPO3エクステンションの作成
 
イマドキなCMS案件のステークホルダー + 私の考えるCMS
イマドキなCMS案件のステークホルダー + 私の考えるCMSイマドキなCMS案件のステークホルダー + 私の考えるCMS
イマドキなCMS案件のステークホルダー + 私の考えるCMS
 
Elggで作るソーシャルメディアWeb
Elggで作るソーシャルメディアWebElggで作るソーシャルメディアWeb
Elggで作るソーシャルメディアWeb
 
eZ Publish 実装 はじめの一歩
eZ Publish 実装 はじめの一歩eZ Publish 実装 はじめの一歩
eZ Publish 実装 はじめの一歩
 
eZ Publish ディスクール (デモ付き)@OSC 2009 Tokyo
eZ Publish ディスクール (デモ付き)@OSC 2009 TokyoeZ Publish ディスクール (デモ付き)@OSC 2009 Tokyo
eZ Publish ディスクール (デモ付き)@OSC 2009 Tokyo
 

Recently uploaded

20240412_HCCJP での Windows Server 2025 Active Directory
20240412_HCCJP での Windows Server 2025 Active Directory20240412_HCCJP での Windows Server 2025 Active Directory
20240412_HCCJP での Windows Server 2025 Active Directoryosamut
 
Amazon SES を勉強してみる その12024/04/12の勉強会で発表されたものです。
Amazon SES を勉強してみる その12024/04/12の勉強会で発表されたものです。Amazon SES を勉強してみる その12024/04/12の勉強会で発表されたものです。
Amazon SES を勉強してみる その12024/04/12の勉強会で発表されたものです。iPride Co., Ltd.
 
スマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムスマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムsugiuralab
 
UPWARD_share_company_information_20240415.pdf
UPWARD_share_company_information_20240415.pdfUPWARD_share_company_information_20240415.pdf
UPWARD_share_company_information_20240415.pdffurutsuka
 
Postman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By DanielPostman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By Danieldanielhu54
 
PHP-Conference-Odawara-2024-04-000000000
PHP-Conference-Odawara-2024-04-000000000PHP-Conference-Odawara-2024-04-000000000
PHP-Conference-Odawara-2024-04-000000000Shota Ito
 
新人研修のまとめ 2024/04/12の勉強会で発表されたものです。
新人研修のまとめ       2024/04/12の勉強会で発表されたものです。新人研修のまとめ       2024/04/12の勉強会で発表されたものです。
新人研修のまとめ 2024/04/12の勉強会で発表されたものです。iPride Co., Ltd.
 
IoT in the era of generative AI, Thanks IoT ALGYAN.pptx
IoT in the era of generative AI, Thanks IoT ALGYAN.pptxIoT in the era of generative AI, Thanks IoT ALGYAN.pptx
IoT in the era of generative AI, Thanks IoT ALGYAN.pptxAtomu Hidaka
 
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略Ryo Sasaki
 

Recently uploaded (9)

20240412_HCCJP での Windows Server 2025 Active Directory
20240412_HCCJP での Windows Server 2025 Active Directory20240412_HCCJP での Windows Server 2025 Active Directory
20240412_HCCJP での Windows Server 2025 Active Directory
 
Amazon SES を勉強してみる その12024/04/12の勉強会で発表されたものです。
Amazon SES を勉強してみる その12024/04/12の勉強会で発表されたものです。Amazon SES を勉強してみる その12024/04/12の勉強会で発表されたものです。
Amazon SES を勉強してみる その12024/04/12の勉強会で発表されたものです。
 
スマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムスマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システム
 
UPWARD_share_company_information_20240415.pdf
UPWARD_share_company_information_20240415.pdfUPWARD_share_company_information_20240415.pdf
UPWARD_share_company_information_20240415.pdf
 
Postman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By DanielPostman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By Daniel
 
PHP-Conference-Odawara-2024-04-000000000
PHP-Conference-Odawara-2024-04-000000000PHP-Conference-Odawara-2024-04-000000000
PHP-Conference-Odawara-2024-04-000000000
 
新人研修のまとめ 2024/04/12の勉強会で発表されたものです。
新人研修のまとめ       2024/04/12の勉強会で発表されたものです。新人研修のまとめ       2024/04/12の勉強会で発表されたものです。
新人研修のまとめ 2024/04/12の勉強会で発表されたものです。
 
IoT in the era of generative AI, Thanks IoT ALGYAN.pptx
IoT in the era of generative AI, Thanks IoT ALGYAN.pptxIoT in the era of generative AI, Thanks IoT ALGYAN.pptx
IoT in the era of generative AI, Thanks IoT ALGYAN.pptx
 
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
 

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

  • 1. 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 要件に eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 2. 対応することができます。しかし、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 フレームワ ークでどう開発を行うか?をお見せします。 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 3. eZ Publish extension とは? extension のサンプルにとりかかる前に、extension の概要と構造について説明します。 extension を作成すると eZ Publish の機能追加、または既存機能の拡張を行うことができます。extension を利用により eZ Publish の本体ファイルを変更することなく、 Publish のコア機能を拡張することが eZ できます。そのため、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/も利用する 場合があります。 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 4. 新しい 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 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 5. 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 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 6. 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']; 上記のようなパラメータアクセスを順番付け有りパラメータ(オーダード・パラメーター)と呼びます。 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 7. 順番付け無しパラメータ(アンオーダード・パラメーター)は順番付け有りパラメータとは違い、名前 と値のペアで構成されます。例えば下記のようになります。 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 の構造も)と一緒です。 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 8. ここでスクリーン上でビューリストの呼び出しを表示させるために、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 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 9. 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 にアクセスしてみてください。 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 10. 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 権限を利用可能にします。 また、 (読む)function については匿名ユーザー(Anonymous user)を含め、すべてのユーザー 「read」 に許可を与えます。 権限設定についてより詳しく知りたい方は、チュートリアル「Adding custom security policy limitations to your modules」をチェックしてください。 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 11. テンプレート・システム さて、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 ); eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 12. // ... // 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 のように修正します。 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 13. <?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 といったほとんどのテンプレートで利用できます。 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 14. ビューの作成 さて次に新しいビューを作成してこのサンプルをもっと拡張しましょう。データベース上に配列データ を保存できるように「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'); を利用し ます。 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 15. その他の 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 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 16. データベースへのアクセス さて、データベースに戻りましょう。新しく作った 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'); eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 17. $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-- eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 18. 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' ) ; eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 19. // 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 といったオブジェクトも同様) eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 20. テンプレート・フェッチ機能 注意:カスタム・フェッチ機能の作成については Understanding and developing fetch functions がより 詳しいです。 ここまででパラメータや GET 値や POST 値を新しいビューに表示させる方法を書いてきました。しか し、データベースに格納されたデータを eZ Publish のテンプレートに表示したい場合、ビューのみでハ ンドリングすることができません。 データを取得するには、 の kernel モジュールの機能である fetch を利用します。 eZ (例:{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 機能に対応するヘルプ クラスです。 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 21. <?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 の再発行をしてください。 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 22. テンプレート・オペレータ 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; } eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 23. /** * @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 上のデー eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 25. 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 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)  
  • 26. 最後に この簡単なサンプルにより、 Publish extension の作成についてのテクニックをいくつか学びました。 eZ オリジナルのビューやビューパラメータ、テンプレート・フェッチ機能やテンプレート・オペレータを カスタムモジュールで実現することに加え、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 eZ  Publish の extension 開発   チュートリアル   (原著:  An  Introduction  to  Developing  eZ  Publish  Extensions)