「開発:ブロック」の版間の差分

提供:MoodleDocs
移動先:案内検索
編集の要約なし
編集の要約なし
 
(4人の利用者による、間の217版が非表示)
1行目: 1行目:
作成中です - [[利用者:Mitsuhiro Yoshida|Mitsuhiro Yoshida]] 2009年5月16日 (土) 00:02 (UTC)
''' ブロックの作成に関するステップバイステップガイド '''
''' ブロックの作成に関するステップバイステップガイド '''


原作者: Jon Papaioannou (pj@moodle.org)
原作者: Jon Papaioannou (pj@moodle.org)


このドキュメントでは、Moodleで使用する独自のブロックを開発したい開発者のためのガイドを提供します。ブロックサブシステムは、1.5リリースのため書き換えられ、拡張されたので、このドキュメントは、1.5開発バージョンのMoodle (およびすべての新しいバージョン) のみに適用されます。しかし、あなたがMoodle 1.3および1.4のために書かれたブロックを修正したい場合、最新のバージョンに関するドキュメントを有用だと思うでしょう ([[開発:ブロック/付録B| 付録B]]) をご覧ください。
{{Moodle 1.9}}
 
このドキュメントでは、Moodleで使用する独自ブロックの開発を希望する開発者のためのガイドを提供します。ブロックサブシステムは、1.5リリースのため書き換えおよび拡張されたため、このドキュメントは1.5開発バージョンのMoodle (およびすべての新しいバージョン) のみに適用されます。しかし、あなたがMoodle 1.3および1.4のために書かれたブロックを修正したい場合、最新のバージョンに関するドキュメントを有用だと思うでしょう ([[開発:ブロック/付録B|付録B]]をご覧ください)


The guide is written as an interactive course which aims to develop a configurable, multi-purpose block that displays arbitrary HTML. It's targeted mainly at people with little experience with Moodle or programming in general and aims to show how easy it is to create new blocks for Moodle. A certain small amount of PHP programming knowledge is still required, though.
このガイドは、任意のHTMLを表示できる、設定可能な多目的ブロックの開発を目標としたインタラクティブコースのために執筆されています。また、Moodleまたは一般的なプログラミングに関する多少の経験のある人を対象として、Moodleのブロックを作成することがいかに簡単であるか示すことを目標とします。しかし、少しのPHPプログラミングの知識は必要とします。


Experienced developers and those who just want a reference text should refer to [[Development:Blocks/Appendix_A| Appendix A]] because the main guide has a rather low concentration of pure information in the text.
メインガイドでは、ドキュメントに関する純粋な情報に焦点が置かれていないため、経験豊富な開発者および参考文献のみ閲覧したい方は、[[開発:ブロック/付録A| 付録A]]をご覧ください。


== 基本コンセプト ==
== 基本コンセプト ==


Through this guide, we will be following the creation of an "HTML" block from scratch in order to demonstrate most of the block features at our disposal. Our block will be named "SimpleHTML". This does not constrain us regarding the name of the actual directory on the server where the files for our block will be stored, but for consistency we will follow the practice of using the lowercased form "simplehtml" in any case where such a name is required.
このガイドを通じて、ほとんどのブロックの特徴を自由に実演するため、私たちは、HTMLブロックをスクラッチから作成してみます。私たちのブロックには、「SimpleHTML」というブロック名をつけます。このブロック名は、私たちのブロックが実際に保存されるサーバの実ディレクトリ名に関して、同じディレクトリ名を強制することはありません。しかし、一貫性を保持するため、「simplehtml」を使用することで、Moodleの開発において、どのような場合でも要求される小文字の名前付けに従います。


Whenever we refer to a file or directory name which contains "simplehtml", it's important to remember that ''only'' the "simplehtml" part is up to us to change; the rest is standardized and essential for Moodle to work correctly.
「simplehtml」を含んだ名称のファイルまたはディレクトリを参照する場合、常に私たちが変更する部分は「simplehtml」のみだと記憶に留めることが重要です。残りは、Moodleが正常に動作するため必要な標準化された部分です。


Whenever a file's path is mentioned in this guide, it will always start with a slash. This refers to the Moodle home directory; all files and directories will be referred to with respect to that directory.
このガイドでファイルパスを参照する場合、常にスラッシュ (/) から始まります。これは、Moodleホームディレクトリを参照します。また、すべてのファイルおよびディレクトリは、Moodleホームディレクトリに対して参照されます。


== Ready, Set, Go! ==
== レディ、セット、ゴー! ==


To define a "block" in Moodle, in the most basic case we need to provide just one source code file. We start by creating the directory ''/blocks/simplehtml/'' and creating a file named ''/blocks/simplehtml/'''''block_simplehtml.php''' which will hold our code. We then begin coding the block:
最も基本的な場合、Moodleで「ブロック」を定義するためには、ソースコードファイル1つのみ必要です。ディレクトリ「/blocks/simplehtml」を作成して、その中に私たちのコードを保持する「block_simplehtml.php」というファイルを作成します。それから、私たちは、ブロックのコーディングを始めます:


<code php>
<code php>
30行目: 30行目:
     $this->version = 2004111200;
     $this->version = 2004111200;
   }
   }
   // The PHP tag and the curly bracket for the class definition
   // 次のセクションで、もうひとつの関数が定義されるので、PHPタグおよびクラス定義の波括弧が閉じられています。
  // will only be closed after there is another function added in the next section.
</code>
</code>


The first line is our block class definition; it must be named exactly in the manner shown. Again, only the "simplehtml" part can (and indeed must) change; everything else is standardized.
最初の1行は、ブロッククラス定義です。これは、表示されるのと同じ様式で記述する必要があります。もう一度、あなたは「simplehtml」の部分のみ変更することができます (また、そうすべきです)。他のすべては標準化されています。


Our class is then given a small method: [[Development:Blocks/Appendix_A#init.28.29| init()]]. This is essential for all blocks, and its purpose is to set the two class member variables listed inside it. But what do these values actually mean? Here's a more detailed description.
そして、私たちのクラスは、小さなメソッドが与えられます: [[開発:ブロック/付録A#init.28.29| init()]]。これは、すべてのブロックに必要なメソッドであり、内部に2つのクラスメンバ変数を設定することが目的です。しかし、これらの変数の本当の意味は何でしょう? 詳細は、下記をご覧ください。


[[Development:Blocks/Appendix_A#.24this-.3Etitle| $this->title]] is the title displayed in the header of our block. We can set it to whatever we like; in this case it's set to read the actual title from a language file we are presumably distributing together with the block. I 'll skip ahead a bit here and say that if you want your block to display '''no''' title at all, then you should set this to any descriptive value you want (but '''not''' make it an empty string). We will later see [[Development:Blocks#Eye_Candy| how to disable the title's display]].
[[開発:ブロック/付録A#.24this-.3Etitle| $this->title]]は、私たちのブロックヘッダに表示されるタイトルです。私たちは、どのようなタイトルでも設定することができます。この場合、恐らくブロックと共に提供される言語ファイルから実際のタイトルが取得されます。あなたがブロックタイトルに何も「表示したくない」場合、ここに説明的な値を入力してください (しかし、空のストリングにはしないでください)。では、先に進みましょう。タイトルを表示しない方法に関して、後ほど[[開発:ブロック#Eye_Candy|タイトル表示を無効にする方法]]を参照します。


[[Development:Blocks/Appendix_A#.24this-.3Eversion| $this->version]] is the version of our block. This actually would only make a difference if your block wanted to keep its own data in special tables in the database (i.e. for very complex blocks). In that case the version number is used exactly as it's used in activities; an upgrade script uses it to incrementally upgrade an "old" version of the block's data to the latest. We will outline this process further ahead, since blocks tend to be relatively simple and not hold their own private data.
[[開発:ブロック/付録A#.24this-.3Eversion| $this->version]]は、私たちのブロックのバージョンです。実際には、あなたのブロックがデータベースの特別テーブルに独自のデータを保持したい場合のみ重要です (例 非常に複雑なブロック)。その場合、バージョンナンバーは、活動で使用されるのと全く同じように使用されます。「古い」バージョンのブロックデータを最新のデータに増分アップグレードするため、アップグレードスクリプトがバージョンナンバーを使用します。ブロックは、比較的シンプルで自データを保持しない傾向にありますので、私たちは、この処理に関する概要を後で説明します。


In our example, this is certainly the case so we just set [[Development:Blocks/Appendix_A#.24this-.3Eversion| $this->version]] to '''YYYYMMDD00''' and forget about it.
私たちの例では、正に前述の例に該当しますので、[[開発:ブロック/付録A#.24this-.3Eversion| $this->version]]'''YYYYMMDD00'''をセットして、後は忘れることにします。


'''UPDATING:'''<br />  
'''アップデート:'''<br />  
Prior to version 1.5, the basic structure of each block class was slightly different. Refer to [[Development:Blocks/Appendix_B| Appendix B]] for more information on the changes that old blocks have to make to conform to the new standard.
バージョン 1.5以前では、それぞれのブロッククラスの基本構造は、若干異なっていました。古いブロックを新しい標準に準拠させるための変更の詳細は[[開発:ブロック/付録B| 付録B]]をご覧ください。


== I Just Hear Static ==
== 私には雑音 (Static) が聴こえるだけ ==
In order to get our block to actually display something on screen, we need to add one more method to our class (before the final closing brace in our file). The new code is:
ブロックが画面で何かを表示するため、私たちは、さらに1つのメソッドを (右中括弧が閉じる前に) クラスに追加する必要があります。新しいコードは以下のとおりです:


<code php>   
<code php>   
66行目: 65行目:
?>  </code>
?>  </code>


It can't get any simpler than that, can it? Let's dissect this method to see what's going on...
これよりシンプルにはなりません、そうでしょ? 何が起きるか、このメソッドを解剖してみましょう ...


First of all, there is a check that returns the current value of [[Development:Blocks/Appendix_A#.24this-.3Econtent| $this->content]] if it's not NULL; otherwise we proceed with "computing" it. Since the computation is potentially a time-consuming operation and it '''will''' be called several times for each block (Moodle works that way internally), we take a precaution and include this time-saver.
まず第一に、値がNULLではない場合、[[開発:ブロック/付録A#.24this-.3Econtent| $this->content]]の現在値を返すチェックがあります。そうでない場合、私たちはこの値を計算し始めます。計算には、潜在的に多大な時間を要して、それぞれのブロックで複数回コールされるため (そのようにMoodleが内部で動かします)、私たちは予防措置として、この時間節約の手段を含むようにします。コンテンツが計算されていない場合 (NULLの場合)、私たちは最初から定義します。そこでは、コード自体が語りますので、それほど語ることはありません。必要であれば、私たちは、HTMLをテキストおよびフッタで使用できるということに留意してください。
Supposing the content had not been computed before (it was NULL), we then define it from scratch. The code speaks for itself there, so there isn't much to say. Just keep in mind that we can use HTML both in the text '''and''' in the footer, if we want to.


At this point our block should be capable of being automatically installed in Moodle and added to courses; visit your administration page to install it (Click "Notifications" under the Site Administration Block) and after seeing it in action come back to continue our tutorial.
この時点で、私たちのブロックは、Moodleに自動的にインストールされ、コースに追加することができます。管理ページに移動して、ブロックのインストール (サイト管理ブロック内の「通知」をクリック) を確認した後、このチュートリアル (ドキュメント) に戻ってください。


== Configure That Out ==
== 設定しよう ==


The current version of our block doesn't really do much; it just displays a fixed message, which is not very useful. What we 'd really like to do is allow the teachers to customize what goes into the block. This, in block-speak, is called "instance configuration". So let's give our block some instance configuration...
私たちのブロックの現在のバージョンでは、それほど多くのことはできません。非常に有用であるとは言えない固定メッセージを表示するのみです。私たちが本当にやりたいことは、教師がブロック内に入れるものをカスタマイズできるようにすることです。このブロックとの会話は、「インスタンス設定」と呼ばれます。それでは、私たちのブロックにインスタンス設定を与えてみましょう ...
First of all, we need to tell Moodle that we want it to provide instance-specific configuration amenities to our block. That's as simple as adding one more method to our block class:
まず第一に、Moodleに対して、私たちのブロックにインスタンス固有の設定装備を提供したいと伝える必要があります。 これは、私たちのブロッククラスに、もうひとつのメソッドを追加するのと同じくらい簡単です:


<code php>
<code php>
84行目: 82行目:
</code>
</code>


This small change is enough to make Moodle display an "Edit..." icon in our block's header when we turn editing mode on in any course. However, if you try to click on that icon you will be presented with a notice that complains about the block's configuration not being implemented correctly. Try it, it's harmless.
編集モードの開始」ボタンをクリックした場合、すべてのコースにおいて、「私たちのブロックヘッダに「編集 ...」アイコンを表示するには、少しの修正のみで十分です。しかし、あなたがそのアイコンをクリックした場合、ブロック設定が正しく実装されていない旨、警告が表示されてしまいます。挑戦してみましょう、安全です。Moodleの苦情は当然です。私たちは設定を必要だと伝えたのに、「どのような」設定が欲しいのか伝えていません。また、何を表示したいかも伝えていません。そのためには、さらに1つのファイルを作成する必要があります: <span class="filename">/blocks/simplehtml/'''config_instance.html'''</span> (正確にこのファイル名にしてください)。差し当たり、以下をコピーしてファイルに貼り付けた後、保存してください:
Moodle's complaints do make sense. We told it that we want to have configuration, but we didn't say ''what'' kind of configuration we want, or how it should be displayed. To do that, we need to create one more file: <span class="filename">/blocks/simplehtml/'''config_instance.html'''</span> (which has to be named exactly like that). For the moment, copy paste the following into it and save:
 
<code php>
<code php>
<table cellpadding="9" cellspacing="0">
<table cellpadding="9" cellspacing="0">
107行目: 104行目:
</code>
</code>


It isn't difficult to see that the above code just provides us with a wysiwyg-editor-enabled textarea to write our block's desired content in and a submit button to save. But... what's $this->config->text? Well...
上記コードを読む限り、WYSIWYGエディタが有効にされたtextareaで、私たちのブロックに必要なコンテンツを記述して、保存ボタンをクリックすることは難しいことではありません。しかし ... $this->config->text とは何でしょう? そうですね ... Moodleでは、ブロック開発者がブロックを簡単に開発できるようにしています。実際には、textareaが「text」と名前付けされていることに気付きましたか? 送信ボタンがクリックされた場合、Moodleは'''config_instance.html'''ファイルで探すことのできる、すべてのフィールドを設定データのインスタンスとして保存します。
Moodle goes a long way to make things easier for block developers. Did you notice that the textarea is actually named "text"? When the submit button is pressed, Moodle saves each and every field it can find in our '''config_instance.html''' file as instance configuration data.


We can then access that data as '''$this->config->''variablename''''', where ''variablename'' is the actual name we used for our field; in this case, "text". So in essence, the above form just pre-populates the textarea with the current content of the block (as indeed it should) and then allows us to change it.
そして、私たちは'''$this->config->''variablename'''''としてデータにアクセスすることができます。ここで「''variablename''」は、私たちのフィールドに使用する実フィールド名です。この場合、"text"となります。ですから、基本的に上記のフォームでは、現在のブロックコンテンツ (そのまま) と共にテキストエリアをプレ実装して、私たちがコンテンツを変更できるようにします。


You also might be surprised by the presence of a submit button and the absence of any <form> element at the same time. But the truth is, we don't need to worry about that at all; Moodle goes a really long way to make things easier for developers! We just print the configuration options we want, in any format we want; include a submit button, and Moodle will handle all the rest itself. The instance configuration variables are automatically at our disposal to access from any of the class methods ''except'' [[Development:Blocks/Appendix_A#init.28.29| init()]].
あなたは、送信ボタンが存在して、<form>エレメントが存在しないことにも驚いていることでしょう。しかし、私たちが全く心配する必要がないことも真実です。長期に渡り、Moodleは開発者が簡単に開発できるよう、発展してきました! 私たちに必要なことは、どのようなフォーマットであれ、送信ボタンを含んだ必要な設定オプションを表示することです。Moodleは、残りすべてを自ら処理します。インスタンス設定変数は、[[開発:ブロック/付録A#init.28.29| init()]]以外、自由にすべてのクラスメソッドからアクセスすることができます。


In the event where the default behavior is not satisfactory, we can still override it. However, this requires advanced modifications to our block class and will not be covered here; refer to [[Development:Blocks/Appendix_A| Appendix A]] for more details.
イベントのデフォルトの動作に満足できない場合、私たちはオーバーライドすることができます。しかし、オーバーライドするためには、私たちのブロックに関して、高度な修正が必要であり、ここでは取り上げられていません。詳細は、[[開発:ブロック/付録A| 付録A]]をご覧ください。
Having now the ability to refer to this instance configuration data through [[Development:Blocks/Appendix_A#.24this-.3Econfig| $this->config]], the final twist is to tell our block to actually ''display'' what is saved in its configuration data. To do that, find this snippet in ''/blocks/simplehtml/block_simplehtml.php'':
[[開発:ブロック/付録A#.24this-.3Econfig| $this->config]]を通して、このインスタンス設定データを参照できるようになります。最後の工夫は、私たちのブロックに対して、設定データに保存された内容を「表示すること」を実際に伝えることです。伝えるには、''/blocks/simplehtml/block_simplehtml.php''の中にある、このスニペットを見つけてください:


<code php>
<code php>
123行目: 119行目:
</code>
</code>


and change it to:
そして、以下のように変更します:


<code php>
<code php>
131行目: 127行目:
</code>
</code>


Oh, and since the footer isn't really exciting at this point, we remove it from our block because it doesn't contribute anything. We could just as easily have decided to make the footer configurable in the above way, too. So for our latest code, the snippet becomes:
おや、この時点でフッタは実際に存在していません。役立つことはありませんので、私たちのブロックからフッタを取り除きます。私たちは、上記と同じように簡単にフッタ設定を決定することができます。ですから、私たちの最新のコード、スニペットは以下のようになります:


<code php>
<code php>
139行目: 135行目:
</code>
</code>


After this discussion, our block is ready for prime time! Indeed, if you now visit any course with a SimpleHTML block, you will see that modifying its contents is now a snap.
このディスカッションの後、私たちのブロックはゴールデンタイムに入ります! あなたが、SimpleHTMLブロックを設置したコースに移動すると、本当にコンテンツの修正は簡単だということを目の当たりにすることでしょう。


[[#top|Back to top of page]]
[[#top|トップページに戻る]]


== The Specialists ==


Implementing instance configuration for the block's contents was good enough to whet our appetite, but who wants to stop there? Why not customize the block's title, too?
== スペシャリスト ==


Why not, indeed. Well, our first attempt to achieve this is natural enough: let's add another field to <span class="filename">/blocks/simplehtml/config_instance.html</span>. Here goes:
ブロックコンテンツのインスタンス設定の実装は、私たちの食欲を満たすには十分でした。しかし、誰がそこで止めたいでしょう? なぜ、ブロックタイトルもカスタマイズしないのでしょう?
 
本当に、なぜ。さて、これに到達するための、私たちの最初の試みは、極めて普通です。別のフィールドを<span class="filename">/blocks/simplehtml/config_instance.html</span>に追加してみましょう。さあ、始めましょう:


<code php>
<code php>
160行目: 157行目:
</code>
</code>


We save the edited file, go to a course, edit the title of the block and... nothing happens! The instance configuration is saved correctly, all right (editing it once more proves that) but it's not being displayed. All we get is just the simple "SimpleHTML" title.
私たちは、編集したファイルを保存して、コースに移動して、ブロックのタイトルを編集して、そして ... 何も起きません! インスタンス設定は、正しく保存され、(念のため再度編集して) すべて問題ありませんが、何も表示されません。単に「SimpleHTML」タイトルが表示されるだけです。


That's not too weird, if we think back a bit. Do you remember that [[Development:Blocks/Appendix_A#init.28.29|init()]] method, where we set [[Development:Blocks/Appendix_A#.24this-.3Etitle|$this->title]]? We didn't actually change its value from then, and [[Development:Blocks/Appendix_A#.24this-.3Etitle|$this->title]] is definitely not the same as '''$this->config->title''' (to Moodle, at least). What we need is a way to update [[Development:Blocks/Appendix_A#.24this-.3Etitle|$this->title]] with the value in the instance configuration. But as we said a bit earlier, we can use [[Development:Blocks/Appendix_A#.24this-.3Econfig| $this->config]] in all methods ''except'' [[Development:Blocks/Appendix_A#init.28.29|init()]]! So what can we do?
少しだけ戻って考えてみれば、これは、とても奇妙だということではありません。私たちが[[開発:ブロック/付録A#.24this-.3Etitle|$this->title]]で設定した[[開発:ブロック/付録A#init.28.29|init()]] メソッドを覚えていますか? 実際、それから私たちは、その設定値を変更していません。また、[[開発:ブロック/付録A#.24this-.3Etitle|$this->title]]は、当然'''$this->config->title''' (少なくともMoodle) と同じではありません。私たちに必要なことは、[[開発:ブロック/付録A#.24this-.3Etitle|$this->title]]のインスタンス設定の値を更新することです。しかし、少し前に述べたように、私たちは、[[開発:ブロック/付録A#init.28.29|init()]]を除くすべてのメソッドで、[[開発:ブロック/付録A#.24this-.3Econfig| $this->config]]を使用することができます! では、私たちには何ができるのでしょうか?


Let's pull out another ace from our sleeve, and add this small method to our block class:
私たちの袖から別のエースを取り出してみましょう。そして、この小さなメソッドを私たちのブロッククラスに追加してみましょう:


<code php>
<code php>
179行目: 176行目:
</code>
</code>


Aha, here's what we wanted to do all along! But what's going on with the [[Development:Blocks/Appendix_A#specialization.28.29| specialization()]] method?
なるほど、私たちが最初からずっとやりたかったことですね! しかし、[[開発:ブロック/付録A#specialization.28.29| specialization()]] メソッドで何が起きるのでしょう?


This "magic" method has actually a very nice property: it's ''guaranteed'' to be automatically called by Moodle as soon as our instance configuration is loaded and available (that is, immediately after [[Development:Blocks/Appendix_A#init.28.29|init()]] is called). That means before the block's content is computed for the first time, and indeed before ''anything'' else is done with the block. Thus, providing a [[Development:Blocks/Appendix_A#specialization.28.29| specialization()]] method is the natural choice for any configuration data that needs to be acted upon "as soon as possible", as in this case.
「魔法の」メソッドは、実際に極めて素晴らしい特性を持っています。私たちのインスタンス設定がロードされ、利用されるようになるとすぐに (つまり、[[開発:ブロック/付録A#init.28.29|init()]]がコールされるとすぐに)、Moodleから自動的にコールされることが「保証」されています。これは、ブロックコンテンツが最初に計算されること、そして本当にブロックに関して、何らかの処理が実行される前を意味します。従って、この場合、「可能な限り速やか」に実行される、すべてのデータ設定に関して[[開発:ブロック/付録A#specialization.28.29| specialization()]] メソッドを提供することは、自然な選択と言えます。


== Now You See Me, Now You Don't ==
== あなたには私が見える、そして、あなたには私が見えなくなる (Now You See Me, Now You Don't) ==


Now would be a good time to mention another nifty technique that can be used in blocks, and which comes in handy quite often. Specifically, it may be the case that our block will have something interesting to display some of the time; but in some other cases, it won't have anything useful to say. (An example here would be the "Recent Activity" block, in the case where no recent activity in fact exists.
さて、ブロックで使用することのできる、別の素晴らしいテクニック、そして、かなり頻繁に役立つテクニックに関して、話してみるのに良い時間になりました。特に、時々私たちのブロックは、興味深いものを表示します。しかし、有益ではないものを表示する場合もあります (例えば、「最近の活動」ブロックで実際に表示するものがない場合です)。


However in that case the block chooses to explicitly inform you of the lack of said activity, which is arguably useful). It would be nice, then, to be able to have our block "disappear" if it's not needed to display it.
しかし、この場合、ブロックは前述の活動の欠如に関して、あなたに明確に伝えることを選んだわけで、これはほぼ間違いなく有用ではあります。そして、表示する必要のないブロックを「非表示にする」ことは、素晴らしいことです。


This is indeed possible, and the way to do it is to make sure that after the [[Development:Blocks/Appendix_A#get_content.28.29| get_content()]] method is called, the block is completely void of content. Specifically, "void of content" means that both $this->content->text and $this->content->footer are each equal to the empty string (<nowiki>''</nowiki>). Moodle performs this check by calling the block's [[Development:Blocks/Appendix_A#is_empty.28.29| is_empty()]] method, and if the block is indeed empty then it is not displayed at all.
これは、実際に可能です。その方法は、[[開発:ブロック/付録A#get_content.28.29| get_content()]]メソッドがコールされた後、ブロックの中身を完全にないようにすることです。具体的に「中身がない」とは、$this->content->textおよび$this->content->footerThisの両者が、それぞれ空のストリング (<nowiki>''</nowiki>) になっていることです。Moodleは、 [[開発:ブロック/付録A#is_empty.28.29| is_empty()]] メソッドをコールすることにより、この状態を確認します。そして、ブロックが空の場合、実際に全く何も表示されません。


Note that the exact value of the block's title and the presence or absence of a [[Development:Blocks/Appendix_A#hide_header.28.29| hide_header()]] method do ''not'' affect this behavior. A block is considered empty if it has no content, irrespective of anything else.
ブロックタイトルの実際の値、[[開発:ブロック/付録A#hide_header.28.29| hide_header()]]メソッドの存在の有無は、この動作に影響を及ぼしませんので留意してください。コンテンツがない場合、他の内容に関わらず、ブロックは空であると判断します。


== We Are Legion ==
== 私たちは軍団 ==


Right now our block is fully configurable, both in title and content. It's so versatile, in fact, that we could make pretty much anything out of it. It would be really nice to be able to add multiple blocks of this type to a single course. And, as you might have guessed, doing that is as simple as adding another small method to our block class:
現在、私たちのブロックはタイトルおよびコンテンツに関して、完全に設定可能な状態です。実際のところ、私たちは非常にほとんどのことを実現することができます。1つのコースに同一ブロックを複数追加できることは大変素晴らしいことです。そして、あなたが推測するように、このようにすることは、私たちのブロックに別の小さなメソッドを追加するくらい非常に簡単です:


<code php>
<code php>
203行目: 200行目:
</code>
</code>


This tells Moodle that it should allow any number of instances of the SimpleHTML block in any course. After saving the changes to our file, Moodle immediately allows us to add multiple copies of the block without further ado!
これにより、すべてのコースにおいて、Moodleは、SimpleHTMLブロックのインスタンスをいくらでも設置することができます。私たちのファイルの変更を保存した後、さらなる騒動なしで、即座に複数のブロックをMoodleで追加することができるようになります!


There are a couple more of interesting points to note here. First of all, even if a block itself allows multiple instances in the same page, the administrator still has the option of disallowing such behavior. This setting can be set separately for each block from the Administration / Configuration / Blocks page.
ここで言及すべき、いくつかの興味深い点があります。まず第一にブロック自体で同一ページに複数インスタンスを許可したとしても、管理者には、そのような挙動を許可しないオプションがあります。この設定は、それぞれのブロックから分離され、「サイト管理 > プラグイン > ブロック > ブロックの管理」にて変更することができます。


And finally, a nice detail is that as soon as we defined an [[Development:Blocks/Appendix_A#instance_allow_multiple.28.29| instance_allow_multiple()]] method, the method [[Development:Blocks/Appendix_A#instance_allow_config.28.29| instance_allow_config()]] that was already defined became obsolete.
そして最後に素晴らしい内容です。私たちが[[開発:ブロック/付録A#instance_allow_multiple.28.29| instance_allow_multiple()]] メソッドを定義するとすぐに、すでに定義されている[[開発:ブロック/付録A#instance_allow_config.28.29| instance_allow_config()]] メソッドは、廃止されてしまいます。


Moodle assumes that if a block allows multiple instances of itself, those instances will want to be configured (what is the point of same multiple instances in the same page if they are identical?) and thus automatically provides an "Edit" icon. So, we can also remove the whole [[Development:Blocks/Appendix_A#instance_allow_config.28.29| instance_allow_config()]] method now without harm. We had only needed it when multiple instances of the block were not allowed.
ブロックに関して、複数インスタンスが許可された場合、「ブロックは設定したいはず」とMoodleは考えます (ブロックが同じ種類の場合、同じページに複数ブロックインスタンスを設置する時のポイントは何でしょう?)。従って、Moodleは自動的に「編集」アイコンを提供します。ですから、私たちは、すべての[[開発:ブロック/付録A#instance_allow_config.28.29| instance_allow_config()]] メソッドを実害なしに取り除くことができるのです。ブロックの複数インスタンスが許可されていない場合のみ、私たちは当該メソッドが必要です。


[[#top|Back to top of page]]
[[#top|トップページに戻る]]


== The Effects of Globalization ==
== グローバリゼーションの効果 ==


Configuring each block instance with its own personal data is cool enough, but sometimes administrators need some way to "touch" all instances of a specific block at the same time. In the case of our SimpleHTML block, a few settings that would make sense to apply to all instances aren't that hard to come up with.
それぞれのブロックインスタンスを独自のパーソナルデータで設定することは、十分に素晴らしいのですが、時々管理者は、特定のブロックに関して、同時にすべてのインスタンスを「触る」方法を必要とするものです。私たちのSimpleHTMLの場合、少しの設定をすべてのインスタンスに適用することは道理にかなっていますし、考え付くことが困難であるというわけでもありません。


For example, we might want to limit the contents of each block to only so many characters, or we might have a setting that filters HTML out of the block's contents, only allowing pure text in. Granted, such a feature wouldn't win us any awards for naming our block "SimpleHTML" but some tormented administrator somewhere might actually find it useful.
例えば、私たちは、それぞれのブロックのコンテンツを文字のみに制限したり、純粋なテキストを使用するため、ブロックコンテンツからHTMLをフィルタすると良いでしょう。確かに、そのような機能は私たちのブロックのネーミング「SimpleHTML」に何ももたらしません。しかし、悩んだ管理者たちは、どこか実際に有益な点を見つけることでしょう。


This kind of configuration is called "global configuration" and applies only to a specific block type (all instances of that block type are affected, however). Implementing such configuration for our block is quite similar to implementing the instance configuration. We will now see how to implement the second example, having a setting that only allows text and not HTML in the block's contents.
このような設定は「グローバル設定」と呼ばれ、特定のブロックタイプにのみ提供されます (しかし、ブロックタイプのすべてのインスタンスが影響を受けます)。そのような設定を私たちのブロックに実装することは、インスタンス設定の実装に極めて似ています。では、私たちは2番目の例の実装方法を見てみましょう。ここでは、ブロックコンテンツに対して、HTMLではなく、テキストのみ許可するよう設定します。
First of all, we need to tell Moodle that we want our block to provide global configuration by, what a surprise, adding a small method to our block class:
まず第一に、これは驚くことなのですが、ブロッククラスに小さなメソッドを追加することで、私たちのブロックにグローバル設定を提供したい旨、Moodleに伝える必要があります::


<code php>  
<code php>  
228行目: 225行目:
</code>
</code>


Then, we need to create a HTML file that actually prints out the configuration screen. In our case, we 'll just print out a checkbox saying "Do not allow HTML in the content" and a "submit" button. Let's create the file <span class="filename">/blocks/simplehtml/config_global.html</span> which again must be named just so, and copy paste the following into it:
それから、実際に設定画面を表示するため、私たちはHTMLファイルを作成する必要があります。私たちのケースでは、「コンテンツにHTMLを許可しない」チェックボックスおよび「送信」ボタンを表示するのみです。それでは、<span class="filename">/blocks/simplehtml/config_global.html</span>という名称のファイルを作成して、下記内容をコピー&ペーストしましょう:
 
[[Development_talk:Blocks|TODO: New settings.php method]]
: Just to note that general documentation about admin settings is at [[Development:Admin_settings#Individual_settings]]. In the absence of documentation, you can look at blocks/course_list, blocks/online_users and blocks/rss_client. They all use a settings.php file.--[[User:Tim Hunt|Tim Hunt]] 19:38, 28 January 2009 (CST)


<code php>
<code php>
246行目: 240行目:
</code>
</code>


True to our block's name, this looks simple enough. What it does is that it displays a checkbox named "block_simplehtml_strict" and if the Moodle configuration variable with the same name (i.e., $CFG->block_simplehtml_strict) is set and not empty (that means it's not equal to an empty string, to zero, or to boolean FALSE) it displays the box as pre-checked (reflecting the current status).
私たちのブロック名に忠実なように、十分にシンプルです。これは、「block_simplehtml_strict」という名称のチェックボックスを表示して、Moodle設定変数に同じ名称の空白ではない値が設定された場合 ($CFG->block_simplehtml_strict) (空白、ゼロまたはブール値のFALSEではない) チェック済みの (現在のステータスを反映した) チェックボックスを表示します。


Why does it check the configuration setting with the same name? Because the default implementation of the global configuration saving code takes all the variables we have in our form and saves them as Moodle configuration options with the same name. Thus, it's good practice to use a descriptive name and also one that won't possibly conflict with the name of another setting.
なぜ、同じ名称の設定をチェックするのですか? グローバル設定のコードを保存するデフォルトでは、私たちのフォームの中にある、すべての変数を取得して、Moodle設定オプションとして同一名で保存するためです。従って、説明的な名称を使うこと、別の設定の名称と衝突する可能性のない名称を使うことは、優れた実践と言えます。


"block_simplehtml_strict" clearly satisfies both requirements.
「block_simplehtml_strict」という名称は、明らかに両者の要件を満たします。


The astute reader may have noticed that we actually have ''two'' input fields named "block_simplehtml_strict" in our configuration file. One is hidden and its value is always 0; the other is the checkbox and its value is 1. What gives? Why have them both there?
目先の利く読者は、実際には「block_simplehtml_strict」という名称の2つの入力フィールドが、私たちの設定ファイルにあることに気付いたことでしょう。1つは隠しフィールドで、その値は常にゼロ、別のフィールドはチェックボックスで、その値は1です。何が起きるのでしょう? なぜ、両方のフィールドがそこにあるのでしょう?


Actually, this is a small trick we use to make our job as simple as possible. HTML forms work this way: if a checkbox in a form is not checked, its name does not appear at all in the variables passed to PHP when the form is submitted. That effectively means that, when we uncheck the box and click submit, the variable is not passed to PHP at all. Thus, PHP does not know to update its value to "0", and our "strict" setting cannot be turned off at all once we turn it on for the first time. Not the behavior we want, surely.
実際のところ、これは私たちの仕事を可能な限り簡単にするための、小さなトリックです。HTMLフォーマットは、次のように動作します: フォーム内のチェックボックスがチェックされていない場合、フォーム送信時、PHPに渡される変数の中にチェックボックスの名称は全く出現しません。これは事実上、私たちがチェックボックスのチェックを外して送信ボタンをクリックした場合、PHPに変数が全く渡されないことを意味します。従って、その値をPHPが「0」に更新する方法を知らないわけで、私たちが最初に「厳密型 (strict)」を有効にした場合、それが無効にされることはありません。もちろん、無効にされることは私たちが望む挙動でもありません。


However, when PHP handles received variables from a form, the variables are processed in the order in which they appear in the form. If a variable comes up having the same name with an already-processed variable, the new value overwrites the old one. Taking advantage of this, our logic runs as follows: the variable "block_simplehtml_strict" is first unconditionally set to "0". Then, ''if'' the box is checked, it is set to "1", overwriting the previous value as discussed. The net result is that our configuration setting behaves as it should.
しかし、フォームから受け取った変数をPHPが処理する場合、フォームで表示される順で変数が処理されます。すでに処理されている変数と同一名の変数を受け取った場合、古い値を新しい値がオーバーライドします。これを利用して、私たちのロジックは、次のようになります: 最初、「block_simplehtml_strict」の値には、無条件にゼロが設定されます。それから、チェックボックスがチェックされた場合、前述のように前の値をオーバーライドして、値には「1」が設定されます。最終結果として、設定値は、私たちの希望通りに設定されます。


To round our bag of tricks up, notice that the use of ''if(!empty($CFG->block_simplehtml_strict))'' in the test for "should the box be checked by default?" is quite deliberate. The first time this script runs, the variable '''$CFG->block_simplehtml_strict''' will not exist at all. After it's set for the first time, its value can be either "0" or "1". Given that both "not set" and the string "0" evaluate as empty while the sting "1" does not, we manage to avoid any warnings from PHP regarding the variable not being set at all, ''and'' have a nice human-readable representation for its two possible values ("0" and "1").
私たちのトリックのバグに対応するには、「デフォルトでチェックボックスがチェックされているか?」をテストするため、「if(!empty($CFG->block_simplehtml_strict))」が使用されている点に注目してください。このスクリプトが最初に実行された場合、変数'''$CFG->block_simplehtml_strict'''は、全く存在していません。そして、最初にその変数が設定された場合、値は「0」または「1」となり得ます。文字列「1」が評価されないのに対して、「設定なし」文字列「0」は両者とも空として評価されます。変数が全く設定されていないというPHPの警告を避けるため、そして可能性のある値 (0または1) に関して、人間が読むことのできる素晴らしい表現を持つため、私たちはこの処理を追加しています。


=== config_save() ===
=== config_save() ===


Now that we have managed to cram a respectable amount of tricks into a few lines of HTML, we might as well discuss the alternative in case that tricks are not enough for a specific configuration setup we have in mind. Saving the data is done in the method [[Development:Blocks/Appendix_A#config_save.28.29| config_save()]], the default implementation of which is as follows:
私たちは、HTMLの少しの行の中に相当量のトリックを何とか詰め込みました。私たちが念頭に置いている特定の設定に対して、トリックが十分でない場合のことを考えて、代わりの方法を議論した方がよさそうです。メソッド[[開発:ブロック/付録A#config_save.28.29| config_save()]]でデータが保存されているため、デフォルトの実装は、以下のようになります:


<code php>  
<code php>  
274行目: 268行目:
</code>
</code>


As can be clearly seen, Moodle passes this method an associative array $data which contains all the variables coming in from our configuration screen. If we wanted to do the job without the "hidden variable with the same name" trick we used above, one way to do it would be by overriding this method with the following:
コードから明らかなように、Moodleはこのメソッドで、私たちの設定画面から取得できるすべての変数を連想配列「$data」に渡しています。私たちが「同一名の変数を隠す」というトリックなしで処理を実行したい場合、1つの方法は、このメソッドを下記のメソッドでオーバーライドすることです:


<code php>
<code php>
287行目: 281行目:
</code>
</code>


Quite straightfoward: if the variable "block_simplehtml_strict" is passed to us, then it can only mean that the user has checked it, so set the configuration variable with the same name to "1". Otherwise, set it to "0". Of course, this version would need to be updated if we add more configuration options because it doesn't respond to them as the default implementation does. Still, it's useful to know how we can override the default implementation if it does not fit our needs (for example, we might not want to save the variable as part of the Moodle configuration but do something else with it).
極めて直接的: 変数「block_simplehtml_strict」が私たちに渡された場合、これはユーザがチェックしたことだけを意味するため、同じ名称の設定変数に「1」をセットします。そうでない場合、「0」をセットします。もちろん、私たちがさらに設定オプションを追加する場合、デフォルトでは反応しないため、このバージョンを更新する必要があります。さらに、私たちの必要性に合致しない場合、デフォルトの実装をどのようにオーバーライドできるか知ることは有用です (例えば、私たちが変数をMoodle設定の一部として保存せず、その変数で他の処理を実行したい場合)


So, we are now at the point where we know if the block should allow HTML tags in its content or not. How do we get the block to actually respect that setting?
私たちは、ブロックがそのコンテンツにHTMLタグを許可べきかどうか知ることのできるポイントまで到着しました。実際、どのようにすれば、ブロックがその設定を留意するようにできるのでしょうか?


We could decide to do one of two things: either have the block "clean" HTML out from the input before saving it in the instance configuration and then display it as-is (the "eager" approach); or have it save the data "as is" and then clean it up each time just before displaying it (the "lazy" approach). The eager approach involves doing work once when saving the configuration; the lazy approach means doing work each time the block is displayed and thus it promises to be worse performance-wise. We shall hence go with the eager approach.
私たちは、次のうち1つを実行することができます: インスタンス設定に保存される前、ブロックがHTMLをクリーニングして、現状のまま表示する (「熱心」なアプローチ) または、データをそのまま保存して、表示される前、毎回クリーニングする (「怠惰」なアプローチ)。「熱心」なアプローチでは、設定保存時、1回のみ処理を必要とします。「怠惰」なアプローチでは、ブロックが表示されるたびに処理が必要となります。ですから、パフォーマンスが悪くなってしまいます。そのため、私たちは「熱心」なアプローチに取り組むべきです。


[[#top|Back to top of page]]
[[#top|トップページに戻る]]


=== instance_config_save() ===
=== instance_config_save() ===
 
私たちは、[[開発:ブロック/付録A#config_save.28.29| config_save()]]をオーバーライドする直前に実行しますが、ここで必要なことは、インスタンスを処理するメソッド、[[開発:ブロック/付録A#instance_config_save.28.29| instance_config_save()]]をオーバーライドすることです。デフォルトの実装は、以下のようになります:
Much as we did just before with overriding [[Development:Blocks/Appendix_A#config_save.28.29| config_save()]], what is needed here is overriding the method [[Development:Blocks/Appendix_A#instance_config_save.28.29| instance_config_save()]] which handles the instance configuration. The default implementation is as follows:


<code php>
<code php>
311行目: 304行目:
</code>
</code>


This may look intimidating at first (what's all this stripslashes_recursive() and base64_encode() and serialize() stuff?) but do not despair; we won't have to touch any of it. We will only add some extra validation code in the beginning and then instruct Moodle to additionally call this default implementation to do the actual storing of the data. Specifically, we will add a method to our class which goes like this:
最初、(stripslashes_recursive()、base64_encode()、serialize()が影響して?) 脅威に感じるかもしれませんが、どうか絶望しないでださい。私たちは、これらのどれも触る必要はありません。私たちは、いくつかのコードを最初の部分に追加して、加えて実際にデータを保存するため、Moodleにこのデフォルトの実装をコールするよう指示します。具体的に言えば、下記のようなメソッドを私たちのクラスに追加します:
   
   
<code php>
<code php>
326行目: 319行目:
</code>
</code>


At last! Now the administrator has absolute power of life and death over what type of content is allowed in our "SimpleHTML" block! Absolute? Well... not exactly. In fact, if we think about it for a while, it will become apparent that if at some point in time HTML is allowed and some blocks have saved their content with HTML included, and afterwards the administrator changes the setting to "off", this will only prevent subsequent content changes from including HTML. Blocks which already had HTML in their content would continue to display it!
とうとう最後です! 現在、管理者は、私たちの「SimpleHTML」ブロックにどのようなタイプのコンテンツを許可するかに関して、絶対的な生死の権限を持つに至りました! 絶対的な? そうですね ... 厳密に言えば違います。実際のところ、暫くの間、私たちがそのことを考えた場合、ある時点でHTMLが許可され、HTMLを含んだ状態でブロックが保存されます。そして、その後、管理者が設定を「off」にすることにより、その後に続く、HTMLが含まれたコンテンツの変更のみ抑制します。すでにコンテンツにHTMLを含んだブロックでは、表示を継続します!
 
一連の考えを巡らせながら、しばらく前に「怠惰」なアプローチを選択したのであれば、この問題を経験しないことに気付くことが次の停止位置です。なぜなら私たちは、それぞれのブロックコンテンツが表示される直前に「サニタイズ」するからです。
 
私たちが「熱心」なアプローチでやれる唯一のことは、管理設定が「HTML off」に変更された直後に、SimpleHTMLインスタンスすべてのコンテンツから、タグをすべてを取り除くことです。しかし、その時でさえ、私たちが取り除いたタグは、「HTML on」にしても、戻すことはできません。他方、「怠惰」なアプローチは「熱心」なアプローチより遅いですが、多目的に使用できます。私たちは、コンテンツを表示する前、HTMLを取り除くか、保持するか選択することができます。そして、管理者が再度設定をONまたはOFFにしたとしても、HTMLを失うことはありません。開発者の人生が、シンプルで素晴らしいものになったと思いませんか?


Following that train of thought, the next stop is realizing that we wouldn't have this problem if we had chosen the lazy approach a while back, because in that case we would "sanitize" each block's content just before it was displayed.
=== エクササイズ ===


The only thing we can do with the eager approach is strip all the tags from the content of all SimpleHTML instances as soon as the admin setting is changed to "HTML off"; but even then, turning the setting back to "HTML on" won't bring back the tags we stripped away. On the other hand, the lazy approach might be slower, but it's more versatile; we can choose whether to strip or keep the HTML before displaying the content, and we won't lose it at all if the admin toggles the setting off and on again. Isn't the life of a developer simple and wonderful?
私たちは、チュートリアルのこの部分を、読者の強制的なエクササイズで終幕にしましょう:
SimpleHTMLブロックを「正常」に動作させるには、「熱心」なアプローチが、私たちのブロックの既存のインスタンス設定すべてのタグを取り除くことを強化する方法を探す、'''または'''、戻って、代わりに「怠惰」なアプローチを実装する必要があります (ヒント: [[開発:ブロック/付録A#get_content.28.29| get_content()]]メソッドで実行します)。


=== Exercise ===  
=== 更新: ===  
We will let this part of the tutorial come to a close with the obligatory exercise for the reader:
In order to have the SimpleHTML block work "correctly", find out how to strengthen the eager approach to strip out all tags from the existing configuration of all instances of our block, '''or''' go back and implement the lazy approach instead.
(Hint: Do that in the [[Development:Blocks/Appendix_A#get_content.28.29| get_content()]] method.)


=== UPDATING: ===
Moodle 1.5以前のバージョンでは、ファイル''config_global.html''には、単純に''config.html''というファイル名が付けられていました。また、メソッド[[Blocks_Howto#method_config_save| config_save]]および[[Blocks_Howto#method_config_print| config_print]]は、各々'''handle_config'''および'''print_config'''と名前付けられていました。ブロックがMoodle 1.5でも動作するようにするには、こられの名前付けを含めたアップグレードが必要となります。詳細は、([[開発:ブロック/付録B|付録B]]をご覧くださいをご覧ください。
Prior to version 1.5, the file ''config_global.html'' was named simply ''config.html''. Also, the methods [[Blocks_Howto#method_config_save| config_save]] and [[Blocks_Howto#method_config_print| config_print]] were named '''handle_config''' and '''print_config''' respectively. Upgrading a block to work with Moodle 1.5 involves updating these aspects; refer to [[Blocks_Howto#appendix_b| Appendix B]] for more information.


== Eye Candy ==
== 目の保養 (Eye Candy) ==


Our block is just about complete functionally, so now let's take a look at some of the tricks we can use to make its behavior customized in a few more useful ways.
私たちのブロックは、ほとんど完璧に動作するようになりました。それでは、さらに何箇所か便利にできるよう、私たちが使用できるトリックを見てみましょう。


First of all, there are a couple of ways we can adjust the visual aspects of our block. For starters, it might be useful to create a block that doesn't display a header (title) at all. You can see this effect in action in the Course Description block that comes with Moodle. This behavior is achieved by, you guessed it, adding one more method to our block class:
私たちのブロックの視覚的側面を調整できる、いくつかの方法があります。まず第一に、ヘッダ (タイトル) を全く表示しないブロックを作成できると便利でしょう。あなたは、この内容をMoodleに実装されている「コース説明」ブロックで見ることができます。この動作は、あなたの予想どおり、私たちのブロッククラスに、さらに1つのメソッドを追加することで実現できます:


<code php>
<code php>
352行目: 346行目:
</code>
</code>


One more note here: we cannot just set an empty title inside the block's [[Development:Blocks/Appendix_A#init.28.29| init()]] method; it's necessary for each block to have a unique, non-empty title after [[Development:Blocks/Appendix_A#init.28.29| init()]] is called so that Moodle can use those titles to differentiate between all of the installed blocks.
ここでもう一つ: 私たちは、空のタイトルをブロックの[[開発:ブロック/付録A#init.28.29| init()]]メソッドに設定することはできません。すべてのインストール済みブロックで、Moodleが異なるタイトルを使用できるよう、[[開発:ブロック/付録A#init.28.29| init()]]がコールされた後、それぞれのブロックがユニークなタイトルを持つ必要があります。


Another adjustment we might want to do is instruct our block to take up a certain amount of width on screen. Moodle handles this as a two-part process: first, it queries each block about its preferred width and takes the maximum number as the desired value. Then, the page that's being displayed can choose to use this value or, more probably, bring it within some specific range of values if it isn't already. That means that the width setting is a best-effort settlement; your block can ''request'' a certain width and Moodle will ''try'' to provide it, but there's no guarantee whatsoever about the end result. As a concrete example, all standard Moodle course formats will deliver any requested width between 180 and 210 pixels, inclusive.
私たちが実施したい、もう一つの調整は、私たちのブロックに画面上での表示幅を教えることです。Moodleは、これを2つのプロセスで処理します: まず最初に、それぞれのブロックに推奨幅を問い合わせて、最大値を望ましい値として記憶します。それから、表示されるページが、この値を使用できるようにするか、こちらが最もあり得るのですが、推奨幅がない場合、特定の範囲の値を取得します。これは、表示幅の設定が最善努力型 (best-effort) の合意であることを意味します。あなたのブロックは、特定の表示幅を「リクエスト」することができます。Moodleは、「リクエスト」された表示幅を提供できるよう「試みます」が、結果に関して、一切保障はありません。具体的な例として、すべての標準的なMoodleコースフォーマットでは、リクエストされた表示幅を、180から210ピクセルの間で提供します。


To instruct Moodle about our block's preferred width, we add one more method to the block class:
私たちの推奨幅をブロックに教えるには、さらに1つのメソッドをブロッククラスに追加する必要があります:


<code php>
<code php>
364行目: 358行目:
}
}
</code>
</code>
This will make our block (and all the other blocks displayed at the same side of the page) a bit wider than standard.


Finally, we can also affect some properties of the actual HTML that will be used to print our block. Each block is fully contained within a &lt;table&gt; element, inside which all the HTML for that block is printed. We can instruct Moodle to add HTML attributes with specific values to that container. This would be done to either a) directly affect the end result (if we say, assign bgcolor="black"), or b) give us freedom to customize the end result using CSS (this is in fact done by default as we 'll see below).
これにより、私たちのブロック (およびページの同じ側に表示される、すべてのブロック) は、標準よりも少しだけ幅広くなります。
 
最後に、私たちのブロック表示に使用される、実HTMLのプロパティに影響を及ぼすことができます。それぞれのブロックは、すべて&lt;table&gt;エレメント内に含まれ、その中で、すべてのHTMLが表示されます。そのコンテナに特定の値を持ったHTML属性を追加するよう、私たちは、Moodleに指示することができます。これは、a) 終了結果に直接影響を及ぼす (例えば、bgcolor="black" を割り当てます)、または、b) CSSを使って、終了結果をカスタマイズする自由を私たちに与える CSS (実際のところ、これは下記のようにデフォルトで実施されます)、いずれかの方法を取ることができます。


The default behavior of this feature in our case will assign to our block's container the class HTML attribute with the value "sideblock block_simplehtml" (the prefix "block_" followed by the name of our block, lowercased). We can then use that class to make CSS selectors in our theme to alter this block's visual style (for example, ".sideblock.block_simplehtml { border: 1px black solid}").
私たちの場合、この機能のデフォルトの動作は、ブロックのコンテナに属性「sideblock block_simplehtml」(接頭辞 "block_" の次に私たちの小文字ブロック名が続きます) を持ったHTMLクラスを割り当てることです。そして、このブロックの視覚的スタイルを変更するため、そのクラスを使用して、私たちのテーマ内にCSSセレクタを作成することができます (例えば、".sideblock.block_simplehtml { border: 1px black solid}")


To change the default behavior, we will need to define a method which returns an associative array of attribute names and values. For example, the version
デフォルトの動作を変更するには、私たちは、属性名および値の連想配列を返すメソッドを定義する必要があります。例えば、このバージョンでは、


<code php>
<code php>
382行目: 376行目:
</code>
</code>


will result in a mouseover event being added to our block using JavaScript, just as if we had written the onmouseover="alert(...)" part ourselves in HTML. Note that we actually duplicate the part which sets the class attribute (we want to keep that, and since we override the default behavior it's our responsibility to emulate it if required).
Javaスクリプトを使用したマウスオーバーイベントが、HTML内で「onmouseover="alert(...)"」と記述するのと同じように、私たちのブロックに追加されます。ここで留意すべき点は、私たちがクラス属性をセットする部分を複製することです (私たちは、この属性を保持したいと思います。また、デフォルトの動作をオーバーライドするため、必要であればエミュレートすることが、私たちの責任です)


And the final elegant touch is that we don't set the class to the hard-coded value "block_simplehtml" but instead use the [[Development:Blocks/Appendix_A#name.28.29| name()]] method to make it dynamically match our block's name.
そして、最後にエレガントな手法は、ハードコードされた値「block_simplehtml」にクラスを設定せず、私たちのブロック名に動的に合致させるため、代わりに[[開発:ブロック/付録A#name.28.29| name()]]メソッドを使用することです。


== Authorized Personnel Only ==
== 認証ユーザのみ ==


It's not difficult to imagine a block which is very useful in some circumstances but it simply cannot be made meaningful in others. An example of this would be the "Social Activities" block which is indeed useful in a course with the social format, but doesn't do anything useful in a course with the weeks format. There should be some way of allowing the use of such blocks only where they are indeed meaningful, and not letting them confuse users if they are not.
ある状況において、ブロックが非常に有用であることを想像することは、難しいことではありません。しかし、他のユーザにとって意味あるブロックを作成することは、非常に難しいことです。この例として、ソーシャルフォーマットのコースにとって、非常に使いやすい「社会活動」ブロックがあります。しかし、このブロックは、ウィークリーフォーマットに関して、全く有用なことは実現できません。そのようなブロックは、本当に意味がある場合のみ、使用を許可するという考え方があるでしょう。そして、ブロックの使用に意味がない場合、ユーザを混乱させるべきではありません。


Moodle allows us to declare which course formats each block is allowed to be displayed in, and enforces these restrictions as set by the block developers at all times. The information is given to Moodle as a standard associative array, with each key corresponding to a page format and defining a boolean value (true/false) that declares whether the block should be allowed to appear in that page format.
Moodleでは、どのコースフォーマットでブロックを表示できるか、宣言することができます。そして、ブロック開発者から設定された、この制限を常に強制することができます。この情報は、ページフォーマットに対応するキーおよび、そのページフォーマットでブロックが表示可能かどうか宣言するブール値 (true/false) の定義を持った連想配列として、Moodleに提供されます。


Notice the deliberate use of the term ''page'' instead of ''course'' in the above paragraph. This is because in Moodle 1.5 and onwards, blocks can be displayed in any page that supports them. The best example of such pages are the course pages, but we are not restricted to them. For instance, the quiz view page (the first one we see when we click on the name of the quiz) also supports blocks.
上の段落では、意図的に用語「コース」の代わりに「ページ」を使っていることに注意してください。この理由は、Moodle 1.5以降、ブロックは、サポートされているどのページにも表示できるからです。そのようなページの最良の例は、コースページですが、私たちは、コースページに限定するわけではありません。例えば、小テスト表示ページ (私たちが小テスト名をクリックした後、表示される最初のページ) でも、ブロックをサポートします。


The format names we can use for the pages derive from the name of the script which is actually used to display that page. For example, when we are looking at a course, the script is <span class="filename">/course/view.php</span> (this is evident from the browser's address line). Thus, the format name of that page is '''course-view'''. It follows easily that the format name for a quiz view page is '''mod-quiz-view'''. This rule of thumb does have a few exceptions, however:
私たちがページに使用できるフォーマット名は、実際にページを表示するために使用されるスクリプト名に由来します。例えば、コースでは、そのスクリプトは、<span class="filename">/course/view.php</span> (これは、ブラウザのアドレス行で判断できます) となります。従って、そのページのフォーマット名は、'''course-view'''となります。小テストビューページのフォーマット名は、'''mod-quiz-view'''であると簡単に導くことができます。しかし、サムネイルに関するルールには、少しだけ例外があります:


# The format name for the front page of Moodle is '''site-index'''.
# Moodleフロントページのフォーマット名は、'''site-index'''です。
# The format name for courses is actually not just '''course-view'''<nowiki>; it is </nowiki>'''course-view-weeks''', '''course-view-topics''', etc.
# コースのフォーマット名は、実際には、'''course-view'''<nowiki>だけでなく、</nowiki>'''course-view-weeks''''''course-view-topics'''等です。
# Even though there is no such page, the format name '''all''' can be used as a catch-all option.
# そのようなページがないとしても、フォーマット名'''all'''を包括的なオプションとして使用することができます。


We can include as many format names as we want in our definition of the applicable formats. Each format can be allowed or disallowed, and there are also three more rules that help resolve the question "is this block allowed into this page or not?":
適用可能なフォーマット定義中で、私たちが必要なだけ、フォーマット名を含むことができます。それぞれのフォーマットを許可、不許可にすることができます。また、「このブロックは、このページで許可されますか?」という問題を解決を手助けするため、さらに3つのルールがあります:


# Prefixes of a format name will match that format name; for example, '''mod''' will match all the activity modules. '''course-view''' will match any course, regardless of the course format. And finally, '''site''' will also match the front page (remember that its full format name is '''site-index''').
# フォーマット名の接頭辞は、そのフォーマット名と合致します。例えば、'''mod'''は、活動モジュールと合致します。'''course-view'''は、コースフォーマットに関わらず、すべてのコースに合致します。そして、最後に、'''site'''は、フロントページと合致します (フルフォーマット名は、'''site-index'''であることを記憶してください)
# The more specialized a format name that matches our page is, the higher precedence it has when deciding if the block will be allowed. For example, '''mod''', '''mod-quiz''' and '''mod-quiz-view''' all match the quiz view page. But if all three are present, '''mod-quiz-view''' will take precedence over the other two because it is a better match.
# 私たちのページに合致するよう、フォーマット名を特化するほど、ブロックが許可される場合の決定に関する優先度が高くなります。例えば、'''mod''''''mod-quiz'''および'''mod-quiz-view'''すべて、小テストのビューページに合致します。3つの名称すべてが存在する場合、合致の度合いが高いため、'''mod-quiz-view'''が優先権を得ます。
# The character '''<nowiki>*</nowiki>''' can be used in place of any word. For example, '''mod''' and '''mod-*''' are equivalent. At the time of this document's writing, there is no actual reason to utilize this "wildcard matching" feature, but it exists for future usage.
# 文字 '''<nowiki>*</nowiki>''' は、言葉のどのような場所にも使うことができます。例えば、'''mod''' および '''mod-*''' は、同等です。このドキュメント執筆時点では、この「ワイルドカード合致」機能を使用する実際の理由はありませんが、将来的な利用のため存在していると考えてください。
# The order that the format names appear does not make any difference.
# フォーマット名が表示される順番は関係ありません。
All of the above are enough to make the situation sound complex, so let's look at some specific examples. First of all, to have our block appear '''only''' in the site front page, we would use:
上記すべては、状況を複雑にするのに十分です。そのため、いくつかの具体例を見てみましょう。まず第一に、私たちのブロックをサイトフロントページ'''のみ'''に表示するため、下記の関数を使用します:


<code php>  
<code php>  
414行目: 408行目:
</code>
</code>
   
   
Since '''all''' is missing, the block is disallowed from appearing in ''any'' course format; but then '''site''' is set to TRUE, so it's explicitly allowed to appear in the site front page (remember that '''site''' matches '''site-index''' because it's a prefix).
'''all'''が存在しないため、ブロックは「すべて」のコースフォーマットでは表示されません。しかし、'''site'''にTRUEが設定されているため、サイトフロントページで表示されることが明確に許可されています (接頭辞により、'''site'''は、'''site-index'''に合致することを記憶してください)


For another example, if we wanted to allow the block to appear in all course formats ''except'' social, and also to ''not'' be allowed anywhere but in courses, we would use:
別の例として、ソーシャルフォーマットを除き、すべてのコースフォーマットで、ブロックを表示したい場合、また、コース以外では表示を「許可したくない」場合、私たちは次のように記述します:


<code php>  
<code php>  
426行目: 420行目:
</code>
</code>


This time, we first allow the block to appear in all courses and then we explicitly disallow the social format.
今回、私たちは、すべてのコースでブロックの表示を許可して、ソーシャルフォーマットでの表示を許可しません。最後に最も複雑な例。サイトフロントページ、コース (ソーシャルコースではなく) そしてまた、小テストを除いて、すべての活動モジュールの表示時に、ブロック表示をサポートします。これは、次のようになります:
For our final, most complicated example, suppose that a block can be displayed in the site front page, in courses (but not social courses) and also when we are viewing any activity module, ''except'' quiz. This would be:
   
   
<code php>
<code php>
441行目: 434行目:
</code>
</code>


It is not difficult to realize that the above accomplishes the objective if we remember that there is a "best match" policy to determine the end result.
最終結果の決定に「ベストマッチ」ポリシーがあることを私たちが記憶していれば、上記目標達成を理解することは難しくありません。


'''UPDATING:''' <br />
'''UPDATING:''' <br />
Prior to version 1.5, blocks were only allowed in courses (and in Moodle 1.4, in the site front page). Also, the keywords used to describe the valid course formats at the time were slightly different and had to be changed in order to allow for a more open architecture. Refer to [[Development:Blocks/Appendix_B| Appendix B]] for more information on the changes that old blocks have to make to conform to the new standard.
前のバージョン1.5では、ブロックはコース内のみで許可されていました (そして、Moodle 1.4では、サイトフロントページのみ)。その当時、有効なコースフォーマットを記述するキーワードは、若干異なっていました。また、さらにオープンアーキテクチャを許可するため、変更する必要がありました。古いブロックを新しい標準に適合させるための修正情報に関して、[[開発:ブロック/付録B| Appendix B]]をご覧ください。


== Lists and Icons ==
== リストおよびアイコン ==


In this final part of the guide we will briefly discuss an additional capability of Moodle's block system, namely the ability to very easily create blocks that display a list of choices to the user. This list is displayed with one item per line, and an optional image (icon) next to the item. An example of such a ''list block'' is the standard Moodle "admin" block, which illustrates all the points discussed in this section.
このガイドの最後の部分では、私たちは、Moodleブロックの追加的な機能に関して、短く論じてみます。明確に言うと、ユーザに対して、選択可能なリストを表示するブロックを非常に簡単に作成することのできる機能です。このリストでは、1行あたり1アイテム表示されます。また、アイテムの横に任意のイメージ (アイコン) を置くことができます。このような「リストブロック」の例は、このセクションで論じるすべての点を標準的に含む、Moodle「管理」ブロックです。


As we have seen so far, blocks use two properties of [[Development:Blocks/Appendix_A#.24this-.3Econtent| $this->content]]: "text" and "footer". The text is displayed as-is as the block content, and the footer is displayed below the content in a smaller font size. List blocks use $this->content->footer in the exact same way, but they ignore $this->content->text.
今までのところ、私たちが見てきたように、ブロックは、[[開発:ブロック/付録A#.24this-.3Econtent| $this->content]]に関して、次の2つのプロパティを使います:「text」および「footer」。「text」は、そのままブロックのコンテンツとして、また、「footer」は小さなサイズのフォントで、コンテンツの下に表示されます。リストブロックは、$this->content->footerを全く同じように使用しますが、$this->content->textは、無視します。


Instead, Moodle expects such blocks to set two other properties when the [[Development:Blocks/Appendix_A#get_content.28.29| get_content()]] method is called: $this->content->items and $this->content->icons. $this->content->items should be a numerically indexed array containing elements that represent the HTML for each item in the list that is going to be displayed. Usually these items will be HTML anchor tags which provide links to some page. $this->content->icons should also be a numerically indexed array, with exactly as many items as $this->content->items has. Each of these items should be a fully qualified HTML <img> tag, with "src", "height", "width" and "alt" attributes. Obviously, it makes sense to keep the images small and of a uniform size.
代わりにMoodleは、[[開発:ブロック/付録A#get_content.28.29| get_content()]]がコールされる場合、そのようなブロックに次の2つのプロパティを設定することを要求します: $this->content->items および $this->content->icons です。$this->content->itemsは、表示されることになるリスト内アイテムそれぞれのHTMLを含む数値索引配列である必要があります。通常、これらのタグは、ページのリンクを提供するHTMLアンカータグです。また、$this->content->iconsも$this->content->itemsと明確に同じ数のアイテムを持った数値索引配列である必要があります。これらのアイテムは、「src」「height」「width」および「alt」属性を持った、省略なしのHTML <img>タグである必要があります。もちろん、イメージを小さく、かつ均一なサイズにすることには意味があります。


In order to tell Moodle that we want to have a list block instead of the standard text block, we need to make a small change to our block class declaration. Instead of extending class '''block_base''', our block will extend class '''block_list'''. For example:
私たちが標準的なテキストブロックの代わりにリストブロックを置きたいことをMoodleに伝えるには、ブロッククラス定義を少しだけ修正する必要があります。クラス'''block_base'''を拡張する代わりに、私たちのブロックは、クラス'''block_list'''を拡張します。例えば以下のようになります:


<code php>  
<code php>  
462行目: 455行目:
</code>
</code>


In addition to making this change, we must of course also modify the [[Development:Blocks/Appendix_A#get_content.28.29| get_content()]] method to construct the [[Development:Blocks/Appendix_A#.24this-.3Econtent| $this->content]] variable as discussed above:
In addition to making this change, we must of course also modify the [[開発:ブロック/付録A#get_content.28.29| get_content()]] method to construct the [[開発:ブロック/付録A#.24this-.3Econtent| $this->content]] variable as discussed above:
 
<hr>
加えて,この変更をするためには,当然のことながら,上で議論した[[開発:ブロック/付録A#.24this-.3Econtent| $this->content]] 変数を[[開発:ブロック/付録A#get_content.28.29| get_content()]] に対して修正して,変更し
なくてはなりません.<!-- proposed by hash -->
<hr>
<code php>  
<code php>  
function get_content() {
function get_content() {
484行目: 480行目:
</code>
</code>


To summarize, if we want to create a list block instead of a text block, we just need to change the block class declaration and the [[Development:Blocks/Appendix_A#get_content.28.29| get_content()]] method. Adding the mandatory [[Development:Blocks/Appendix_A#init.28.29| init()]] method as discussed earlier will then give us our first list block in no time!
要約すると、私たちがテキストブロックの代わりに、リストブロックを作成したい場合、ブロッククラス定義および[[開発:ブロック/付録A#get_content.28.29| get_content()]]メソッドを変更する必要があります。私たちが前述した必須の[[開発:ブロック/付録A#init.28.29| init()]]メソッドを追加することで、私たちの最初のリストブロックをすぐに作成することができます!
 
[[#top|トップページに戻る]]
 
{{Moodle 2.0}}


[[#top|Back to top of page]]
; Moodle 2.0
* Moodle2.0用の変更については、[[Development:Migrating contrib code to 2.0]] や Frank Ralf/Experience of converting a module to Moodle 2 https://docs.moodle.org/en/User:Frank_Ralf/Experience_of_converting_a_module_to_Moodle_2 (英語)をご覧ください。


== 付録==
== 付録==


The appendices have been moved to separate pages:
付録は別々のページに移動されました:


* 付録A: [[開発:ブロック/付録A|''block_base'' Reference]]  
* 付録A: [[開発:ブロック/付録A|block_base参照]]  
* 付録B: [[開発:ブロック/付録B|Differences in the Blocks API for Moodle Versions prior to 1.5]]
* 付録B: [[開発:ブロック/付録B|MoodleブロックAPIに関する、1.5以前のバージョンとの違い]]
* 付録C: [[開発:ブロック/付録C|Creating Database Tables for Blocks (prior to 1.7)]]
* 付録C: [[開発:ブロック/付録C|ブロックのデータベーステーブルを作成する (1.7以前)]]





2010年11月23日 (火) 03:57時点における最新版

ブロックの作成に関するステップバイステップガイド

原作者: Jon Papaioannou (pj@moodle.org)

Moodle 1.9


このドキュメントでは、Moodleで使用する独自ブロックの開発を希望する開発者のためのガイドを提供します。ブロックサブシステムは、1.5リリースのため書き換えおよび拡張されたため、このドキュメントは1.5開発バージョンのMoodle (およびすべての新しいバージョン) のみに適用されます。しかし、あなたがMoodle 1.3および1.4のために書かれたブロックを修正したい場合、最新のバージョンに関するドキュメントを有用だと思うでしょう (付録Bをご覧ください)。

このガイドは、任意のHTMLを表示できる、設定可能な多目的ブロックの開発を目標としたインタラクティブコースのために執筆されています。また、Moodleまたは一般的なプログラミングに関する多少の経験のある人を対象として、Moodleのブロックを作成することがいかに簡単であるか示すことを目標とします。しかし、少しのPHPプログラミングの知識は必要とします。

メインガイドでは、ドキュメントに関する純粋な情報に焦点が置かれていないため、経験豊富な開発者および参考文献のみ閲覧したい方は、 付録Aをご覧ください。

基本コンセプト

このガイドを通じて、ほとんどのブロックの特徴を自由に実演するため、私たちは、HTMLブロックをスクラッチから作成してみます。私たちのブロックには、「SimpleHTML」というブロック名をつけます。このブロック名は、私たちのブロックが実際に保存されるサーバの実ディレクトリ名に関して、同じディレクトリ名を強制することはありません。しかし、一貫性を保持するため、「simplehtml」を使用することで、Moodleの開発において、どのような場合でも要求される小文字の名前付けに従います。

「simplehtml」を含んだ名称のファイルまたはディレクトリを参照する場合、常に私たちが変更する部分は「simplehtml」のみだと記憶に留めることが重要です。残りは、Moodleが正常に動作するため必要な標準化された部分です。

このガイドでファイルパスを参照する場合、常にスラッシュ (/) から始まります。これは、Moodleホームディレクトリを参照します。また、すべてのファイルおよびディレクトリは、Moodleホームディレクトリに対して参照されます。

レディ、セット、ゴー!

最も基本的な場合、Moodleで「ブロック」を定義するためには、ソースコードファイル1つのみ必要です。ディレクトリ「/blocks/simplehtml」を作成して、その中に私たちのコードを保持する「block_simplehtml.php」というファイルを作成します。それから、私たちは、ブロックのコーディングを始めます:

<?php class block_simplehtml extends block_base {

 function init() {
   $this->title   = get_string('simplehtml', 'block_simplehtml');
   $this->version = 2004111200;
 }
 // 次のセクションで、もうひとつの関数が定義されるので、PHPタグおよびクラス定義の波括弧が閉じられています。

最初の1行は、ブロッククラス定義です。これは、表示されるのと同じ様式で記述する必要があります。もう一度、あなたは「simplehtml」の部分のみ変更することができます (また、そうすべきです)。他のすべては標準化されています。

そして、私たちのクラスは、小さなメソッドが与えられます: init()。これは、すべてのブロックに必要なメソッドであり、内部に2つのクラスメンバ変数を設定することが目的です。しかし、これらの変数の本当の意味は何でしょう? 詳細は、下記をご覧ください。

$this->titleは、私たちのブロックヘッダに表示されるタイトルです。私たちは、どのようなタイトルでも設定することができます。この場合、恐らくブロックと共に提供される言語ファイルから実際のタイトルが取得されます。あなたがブロックタイトルに何も「表示したくない」場合、ここに説明的な値を入力してください (しかし、空のストリングにはしないでください)。では、先に進みましょう。タイトルを表示しない方法に関して、後ほどタイトル表示を無効にする方法を参照します。

$this->versionは、私たちのブロックのバージョンです。実際には、あなたのブロックがデータベースの特別テーブルに独自のデータを保持したい場合のみ重要です (例 非常に複雑なブロック)。その場合、バージョンナンバーは、活動で使用されるのと全く同じように使用されます。「古い」バージョンのブロックデータを最新のデータに増分アップグレードするため、アップグレードスクリプトがバージョンナンバーを使用します。ブロックは、比較的シンプルで自データを保持しない傾向にありますので、私たちは、この処理に関する概要を後で説明します。

私たちの例では、正に前述の例に該当しますので、 $this->versionYYYYMMDD00をセットして、後は忘れることにします。

アップデート:
バージョン 1.5以前では、それぞれのブロッククラスの基本構造は、若干異なっていました。古いブロックを新しい標準に準拠させるための変更の詳細は 付録Bをご覧ください。

私には雑音 (Static) が聴こえるだけ

ブロックが画面で何かを表示するため、私たちは、さらに1つのメソッドを (右中括弧が閉じる前に) クラスに追加する必要があります。新しいコードは以下のとおりです:

 function get_content() {
   if ($this->content !== NULL) {
     return $this->content;
   }
   $this->content         =  new stdClass;
   $this->content->text   = 'The content of our SimpleHTML block!';
   $this->content->footer = 'Footer here...';

   return $this->content;
 }

} // Here's the closing curly bracket for the class definition

   // and here's the closing PHP tag from the section above.

?>

これよりシンプルにはなりません、そうでしょ? 何が起きるか、このメソッドを解剖してみましょう ...

まず第一に、値がNULLではない場合、 $this->contentの現在値を返すチェックがあります。そうでない場合、私たちはこの値を計算し始めます。計算には、潜在的に多大な時間を要して、それぞれのブロックで複数回コールされるため (そのようにMoodleが内部で動かします)、私たちは予防措置として、この時間節約の手段を含むようにします。コンテンツが計算されていない場合 (NULLの場合)、私たちは最初から定義します。そこでは、コード自体が語りますので、それほど語ることはありません。必要であれば、私たちは、HTMLをテキストおよびフッタで使用できるということに留意してください。

この時点で、私たちのブロックは、Moodleに自動的にインストールされ、コースに追加することができます。管理ページに移動して、ブロックのインストール (サイト管理ブロック内の「通知」をクリック) を確認した後、このチュートリアル (ドキュメント) に戻ってください。

設定しよう

私たちのブロックの現在のバージョンでは、それほど多くのことはできません。非常に有用であるとは言えない固定メッセージを表示するのみです。私たちが本当にやりたいことは、教師がブロック内に入れるものをカスタマイズできるようにすることです。このブロックとの会話は、「インスタンス設定」と呼ばれます。それでは、私たちのブロックにインスタンス設定を与えてみましょう ... まず第一に、Moodleに対して、私たちのブロックにインスタンス固有の設定装備を提供したいと伝える必要があります。 これは、私たちのブロッククラスに、もうひとつのメソッドを追加するのと同じくらい簡単です:

function instance_allow_config() {

 return true;

}

編集モードの開始」ボタンをクリックした場合、すべてのコースにおいて、「私たちのブロックヘッダに「編集 ...」アイコンを表示するには、少しの修正のみで十分です。しかし、あなたがそのアイコンをクリックした場合、ブロック設定が正しく実装されていない旨、警告が表示されてしまいます。挑戦してみましょう、安全です。Moodleの苦情は当然です。私たちは設定を必要だと伝えたのに、「どのような」設定が欲しいのか伝えていません。また、何を表示したいかも伝えていません。そのためには、さらに1つのファイルを作成する必要があります: /blocks/simplehtml/config_instance.html (正確にこのファイル名にしてください)。差し当たり、以下をコピーしてファイルに貼り付けた後、保存してください:

      <?php print_string('configcontent', 'block_simplehtml'); ?>:
      <?php print_textarea(true, 10, 50, 0, 0, 'text', $this->config->text); ?>
     <input type="submit" value="<?php print_string('savechanges') ?>" />

<?php use_html_editor(); ?>

上記コードを読む限り、WYSIWYGエディタが有効にされたtextareaで、私たちのブロックに必要なコンテンツを記述して、保存ボタンをクリックすることは難しいことではありません。しかし ... $this->config->text とは何でしょう? そうですね ... Moodleでは、ブロック開発者がブロックを簡単に開発できるようにしています。実際には、textareaが「text」と名前付けされていることに気付きましたか? 送信ボタンがクリックされた場合、Moodleはconfig_instance.htmlファイルで探すことのできる、すべてのフィールドを設定データのインスタンスとして保存します。

そして、私たちは$this->config->variablenameとしてデータにアクセスすることができます。ここで「variablename」は、私たちのフィールドに使用する実フィールド名です。この場合、"text"となります。ですから、基本的に上記のフォームでは、現在のブロックコンテンツ (そのまま) と共にテキストエリアをプレ実装して、私たちがコンテンツを変更できるようにします。

あなたは、送信ボタンが存在して、<form>エレメントが存在しないことにも驚いていることでしょう。しかし、私たちが全く心配する必要がないことも真実です。長期に渡り、Moodleは開発者が簡単に開発できるよう、発展してきました! 私たちに必要なことは、どのようなフォーマットであれ、送信ボタンを含んだ必要な設定オプションを表示することです。Moodleは、残りすべてを自ら処理します。インスタンス設定変数は、 init()以外、自由にすべてのクラスメソッドからアクセスすることができます。

イベントのデフォルトの動作に満足できない場合、私たちはオーバーライドすることができます。しかし、オーバーライドするためには、私たちのブロックに関して、高度な修正が必要であり、ここでは取り上げられていません。詳細は、 付録Aをご覧ください。 $this->configを通して、このインスタンス設定データを参照できるようになります。最後の工夫は、私たちのブロックに対して、設定データに保存された内容を「表示すること」を実際に伝えることです。伝えるには、/blocks/simplehtml/block_simplehtml.phpの中にある、このスニペットを見つけてください:

$this->content = new stdClass;
$this->content->text   = 'The content of our SimpleHTML block!';
$this->content->footer = 'Footer here...';

そして、以下のように変更します:

$this->content = new stdClass;
$this->content->text   = $this->config->text;
$this->content->footer = 'Footer here...';

おや、この時点でフッタは実際に存在していません。役立つことはありませんので、私たちのブロックからフッタを取り除きます。私たちは、上記と同じように簡単にフッタ設定を決定することができます。ですから、私たちの最新のコード、スニペットは以下のようになります:

$this->content = new stdClass;
$this->content->text   = $this->config->text;
$this->content->footer = ;

このディスカッションの後、私たちのブロックはゴールデンタイムに入ります! あなたが、SimpleHTMLブロックを設置したコースに移動すると、本当にコンテンツの修正は簡単だということを目の当たりにすることでしょう。

トップページに戻る


スペシャリスト

ブロックコンテンツのインスタンス設定の実装は、私たちの食欲を満たすには十分でした。しかし、誰がそこで止めたいでしょう? なぜ、ブロックタイトルもカスタマイズしないのでしょう?

本当に、なぜ。さて、これに到達するための、私たちの最初の試みは、極めて普通です。別のフィールドを/blocks/simplehtml/config_instance.htmlに追加してみましょう。さあ、始めましょう:

<?php print_string('configtitle', 'block_simplehtml'); ?>:

   <input type="text" name="title" size="30" value="<?php echo $this->config->title; ?>" />

私たちは、編集したファイルを保存して、コースに移動して、ブロックのタイトルを編集して、そして ... 何も起きません! インスタンス設定は、正しく保存され、(念のため再度編集して) すべて問題ありませんが、何も表示されません。単に「SimpleHTML」タイトルが表示されるだけです。 少しだけ戻って考えてみれば、これは、とても奇妙だということではありません。私たちが$this->titleで設定したinit() メソッドを覚えていますか? 実際、それから私たちは、その設定値を変更していません。また、$this->titleは、当然$this->config->title (少なくともMoodle) と同じではありません。私たちに必要なことは、$this->titleのインスタンス設定の値を更新することです。しかし、少し前に述べたように、私たちは、init()を除くすべてのメソッドで、 $this->configを使用することができます! では、私たちには何ができるのでしょうか? 私たちの袖から別のエースを取り出してみましょう。そして、この小さなメソッドを私たちのブロッククラスに追加してみましょう: function specialization() { if(!empty($this->config->title)){ $this->title = $this->config->title; }else{ $this->config->title = 'Some title ...'; } if(empty($this->config->text)){ $this->config->text = 'Some text ...'; } } なるほど、私たちが最初からずっとやりたかったことですね! しかし、 specialization() メソッドで何が起きるのでしょう? 「魔法の」メソッドは、実際に極めて素晴らしい特性を持っています。私たちのインスタンス設定がロードされ、利用されるようになるとすぐに (つまり、init()がコールされるとすぐに)、Moodleから自動的にコールされることが「保証」されています。これは、ブロックコンテンツが最初に計算されること、そして本当にブロックに関して、何らかの処理が実行される前を意味します。従って、この場合、「可能な限り速やか」に実行される、すべてのデータ設定に関して specialization() メソッドを提供することは、自然な選択と言えます。

あなたには私が見える、そして、あなたには私が見えなくなる (Now You See Me, Now You Don't)

さて、ブロックで使用することのできる、別の素晴らしいテクニック、そして、かなり頻繁に役立つテクニックに関して、話してみるのに良い時間になりました。特に、時々私たちのブロックは、興味深いものを表示します。しかし、有益ではないものを表示する場合もあります (例えば、「最近の活動」ブロックで実際に表示するものがない場合です)。

しかし、この場合、ブロックは前述の活動の欠如に関して、あなたに明確に伝えることを選んだわけで、これはほぼ間違いなく有用ではあります。そして、表示する必要のないブロックを「非表示にする」ことは、素晴らしいことです。

これは、実際に可能です。その方法は、 get_content()メソッドがコールされた後、ブロックの中身を完全にないようにすることです。具体的に「中身がない」とは、$this->content->textおよび$this->content->footerThisの両者が、それぞれ空のストリング ('') になっていることです。Moodleは、 is_empty() メソッドをコールすることにより、この状態を確認します。そして、ブロックが空の場合、実際に全く何も表示されません。

ブロックタイトルの実際の値、 hide_header()メソッドの存在の有無は、この動作に影響を及ぼしませんので留意してください。コンテンツがない場合、他の内容に関わらず、ブロックは空であると判断します。

私たちは軍団

現在、私たちのブロックはタイトルおよびコンテンツに関して、完全に設定可能な状態です。実際のところ、私たちは非常にほとんどのことを実現することができます。1つのコースに同一ブロックを複数追加できることは大変素晴らしいことです。そして、あなたが推測するように、このようにすることは、私たちのブロックに別の小さなメソッドを追加するくらい非常に簡単です:

function instance_allow_multiple() {

 return true;

}

これにより、すべてのコースにおいて、Moodleは、SimpleHTMLブロックのインスタンスをいくらでも設置することができます。私たちのファイルの変更を保存した後、さらなる騒動なしで、即座に複数のブロックをMoodleで追加することができるようになります!

ここで言及すべき、いくつかの興味深い点があります。まず第一にブロック自体で同一ページに複数インスタンスを許可したとしても、管理者には、そのような挙動を許可しないオプションがあります。この設定は、それぞれのブロックから分離され、「サイト管理 > プラグイン > ブロック > ブロックの管理」にて変更することができます。

そして最後に素晴らしい内容です。私たちが instance_allow_multiple() メソッドを定義するとすぐに、すでに定義されている instance_allow_config() メソッドは、廃止されてしまいます。

ブロックに関して、複数インスタンスが許可された場合、「ブロックは設定したいはず」とMoodleは考えます (ブロックが同じ種類の場合、同じページに複数ブロックインスタンスを設置する時のポイントは何でしょう?)。従って、Moodleは自動的に「編集」アイコンを提供します。ですから、私たちは、すべての instance_allow_config() メソッドを実害なしに取り除くことができるのです。ブロックの複数インスタンスが許可されていない場合のみ、私たちは当該メソッドが必要です。

トップページに戻る

グローバリゼーションの効果

それぞれのブロックインスタンスを独自のパーソナルデータで設定することは、十分に素晴らしいのですが、時々管理者は、特定のブロックに関して、同時にすべてのインスタンスを「触る」方法を必要とするものです。私たちのSimpleHTMLの場合、少しの設定をすべてのインスタンスに適用することは道理にかなっていますし、考え付くことが困難であるというわけでもありません。

例えば、私たちは、それぞれのブロックのコンテンツを文字のみに制限したり、純粋なテキストを使用するため、ブロックコンテンツからHTMLをフィルタすると良いでしょう。確かに、そのような機能は私たちのブロックのネーミング「SimpleHTML」に何ももたらしません。しかし、悩んだ管理者たちは、どこか実際に有益な点を見つけることでしょう。

このような設定は「グローバル設定」と呼ばれ、特定のブロックタイプにのみ提供されます (しかし、ブロックタイプのすべてのインスタンスが影響を受けます)。そのような設定を私たちのブロックに実装することは、インスタンス設定の実装に極めて似ています。では、私たちは2番目の例の実装方法を見てみましょう。ここでは、ブロックコンテンツに対して、HTMLではなく、テキストのみ許可するよう設定します。 まず第一に、これは驚くことなのですが、ブロッククラスに小さなメソッドを追加することで、私たちのブロックにグローバル設定を提供したい旨、Moodleに伝える必要があります::

function has_config() {

 return true;

}

それから、実際に設定画面を表示するため、私たちはHTMLファイルを作成する必要があります。私たちのケースでは、「コンテンツにHTMLを許可しない」チェックボックスおよび「送信」ボタンを表示するのみです。それでは、/blocks/simplehtml/config_global.htmlという名称のファイルを作成して、下記内容をコピー&ペーストしましょう:

<input type="hidden" name="block_simplehtml_strict" value="0" />
<input type="checkbox" name="block_simplehtml_strict" value="1"
  <?php if(!empty($CFG->block_simplehtml_strict)) 
            echo 'checked="checked"'; ?> />
  <?php print_string('donotallowhtml', 'block_simplehtml'); ?>

<input type="submit" value="<?php print_string('savechanges'); ?>" />

私たちのブロック名に忠実なように、十分にシンプルです。これは、「block_simplehtml_strict」という名称のチェックボックスを表示して、Moodle設定変数に同じ名称の空白ではない値が設定された場合 (例 $CFG->block_simplehtml_strict) 、(空白、ゼロまたはブール値のFALSEではない) チェック済みの (現在のステータスを反映した) チェックボックスを表示します。

なぜ、同じ名称の設定をチェックするのですか? グローバル設定のコードを保存するデフォルトでは、私たちのフォームの中にある、すべての変数を取得して、Moodle設定オプションとして同一名で保存するためです。従って、説明的な名称を使うこと、別の設定の名称と衝突する可能性のない名称を使うことは、優れた実践と言えます。

「block_simplehtml_strict」という名称は、明らかに両者の要件を満たします。

目先の利く読者は、実際には「block_simplehtml_strict」という名称の2つの入力フィールドが、私たちの設定ファイルにあることに気付いたことでしょう。1つは隠しフィールドで、その値は常にゼロ、別のフィールドはチェックボックスで、その値は1です。何が起きるのでしょう? なぜ、両方のフィールドがそこにあるのでしょう?

実際のところ、これは私たちの仕事を可能な限り簡単にするための、小さなトリックです。HTMLフォーマットは、次のように動作します: フォーム内のチェックボックスがチェックされていない場合、フォーム送信時、PHPに渡される変数の中にチェックボックスの名称は全く出現しません。これは事実上、私たちがチェックボックスのチェックを外して送信ボタンをクリックした場合、PHPに変数が全く渡されないことを意味します。従って、その値をPHPが「0」に更新する方法を知らないわけで、私たちが最初に「厳密型 (strict)」を有効にした場合、それが無効にされることはありません。もちろん、無効にされることは私たちが望む挙動でもありません。

しかし、フォームから受け取った変数をPHPが処理する場合、フォームで表示される順で変数が処理されます。すでに処理されている変数と同一名の変数を受け取った場合、古い値を新しい値がオーバーライドします。これを利用して、私たちのロジックは、次のようになります: 最初、「block_simplehtml_strict」の値には、無条件にゼロが設定されます。それから、チェックボックスがチェックされた場合、前述のように前の値をオーバーライドして、値には「1」が設定されます。最終結果として、設定値は、私たちの希望通りに設定されます。

私たちのトリックのバグに対応するには、「デフォルトでチェックボックスがチェックされているか?」をテストするため、「if(!empty($CFG->block_simplehtml_strict))」が使用されている点に注目してください。このスクリプトが最初に実行された場合、変数$CFG->block_simplehtml_strictは、全く存在していません。そして、最初にその変数が設定された場合、値は「0」または「1」となり得ます。文字列「1」が評価されないのに対して、「設定なし」文字列「0」は両者とも空として評価されます。変数が全く設定されていないというPHPの警告を避けるため、そして可能性のある値 (0または1) に関して、人間が読むことのできる素晴らしい表現を持つため、私たちはこの処理を追加しています。

config_save()

私たちは、HTMLの少しの行の中に相当量のトリックを何とか詰め込みました。私たちが念頭に置いている特定の設定に対して、トリックが十分でない場合のことを考えて、代わりの方法を議論した方がよさそうです。メソッド config_save()でデータが保存されているため、デフォルトの実装は、以下のようになります:

function config_save($data) {

 // Default behavior: save all variables as $CFG properties
 foreach ($data as $name => $value) {
   set_config($name, $value);
 }
 return true;

}

コードから明らかなように、Moodleはこのメソッドで、私たちの設定画面から取得できるすべての変数を連想配列「$data」に渡しています。私たちが「同一名の変数を隠す」というトリックなしで処理を実行したい場合、1つの方法は、このメソッドを下記のメソッドでオーバーライドすることです:

function config_save($data) {

 if(isset($data['block_simplehtml_strict'])) {
   set_config('block_simplehtml_strict', '1');
 }else {
   set_config('block_simplehtml_strict', '0');
 }
 return true;

}

極めて直接的: 変数「block_simplehtml_strict」が私たちに渡された場合、これはユーザがチェックしたことだけを意味するため、同じ名称の設定変数に「1」をセットします。そうでない場合、「0」をセットします。もちろん、私たちがさらに設定オプションを追加する場合、デフォルトでは反応しないため、このバージョンを更新する必要があります。さらに、私たちの必要性に合致しない場合、デフォルトの実装をどのようにオーバーライドできるか知ることは有用です (例えば、私たちが変数をMoodle設定の一部として保存せず、その変数で他の処理を実行したい場合)。

私たちは、ブロックがそのコンテンツにHTMLタグを許可べきかどうか知ることのできるポイントまで到着しました。実際、どのようにすれば、ブロックがその設定を留意するようにできるのでしょうか?

私たちは、次のうち1つを実行することができます: インスタンス設定に保存される前、ブロックがHTMLをクリーニングして、現状のまま表示する (「熱心」なアプローチ) または、データをそのまま保存して、表示される前、毎回クリーニングする (「怠惰」なアプローチ)。「熱心」なアプローチでは、設定保存時、1回のみ処理を必要とします。「怠惰」なアプローチでは、ブロックが表示されるたびに処理が必要となります。ですから、パフォーマンスが悪くなってしまいます。そのため、私たちは「熱心」なアプローチに取り組むべきです。

トップページに戻る

instance_config_save()

私たちは、 config_save()をオーバーライドする直前に実行しますが、ここで必要なことは、インスタンスを処理するメソッド、 instance_config_save()をオーバーライドすることです。デフォルトの実装は、以下のようになります:

function instance_config_save($data) {

 $data = stripslashes_recursive($data);
 $this->config = $data;
 return set_field('block_instance', 
                  'configdata',
                   base64_encode(serialize($data)),
                  'id', 
                  $this->instance->id);

}

最初、(stripslashes_recursive()、base64_encode()、serialize()が影響して?) 脅威に感じるかもしれませんが、どうか絶望しないでださい。私たちは、これらのどれも触る必要はありません。私たちは、いくつかのコードを最初の部分に追加して、加えて実際にデータを保存するため、Moodleにこのデフォルトの実装をコールするよう指示します。具体的に言えば、下記のようなメソッドを私たちのクラスに追加します:

function instance_config_save($data) {

 // Clean the data if we have to
 global $CFG;
 if(!empty($CFG->block_simplehtml_strict)) {
   $data->text = strip_tags($data->text);
 }
 // And now forward to the default implementation defined in the parent class
 return parent::instance_config_save($data);

}

とうとう最後です! 現在、管理者は、私たちの「SimpleHTML」ブロックにどのようなタイプのコンテンツを許可するかに関して、絶対的な生死の権限を持つに至りました! 絶対的な? そうですね ... 厳密に言えば違います。実際のところ、暫くの間、私たちがそのことを考えた場合、ある時点でHTMLが許可され、HTMLを含んだ状態でブロックが保存されます。そして、その後、管理者が設定を「off」にすることにより、その後に続く、HTMLが含まれたコンテンツの変更のみ抑制します。すでにコンテンツにHTMLを含んだブロックでは、表示を継続します!

一連の考えを巡らせながら、しばらく前に「怠惰」なアプローチを選択したのであれば、この問題を経験しないことに気付くことが次の停止位置です。なぜなら私たちは、それぞれのブロックコンテンツが表示される直前に「サニタイズ」するからです。

私たちが「熱心」なアプローチでやれる唯一のことは、管理設定が「HTML off」に変更された直後に、SimpleHTMLインスタンスすべてのコンテンツから、タグをすべてを取り除くことです。しかし、その時でさえ、私たちが取り除いたタグは、「HTML on」にしても、戻すことはできません。他方、「怠惰」なアプローチは「熱心」なアプローチより遅いですが、多目的に使用できます。私たちは、コンテンツを表示する前、HTMLを取り除くか、保持するか選択することができます。そして、管理者が再度設定をONまたはOFFにしたとしても、HTMLを失うことはありません。開発者の人生が、シンプルで素晴らしいものになったと思いませんか?

エクササイズ

私たちは、チュートリアルのこの部分を、読者の強制的なエクササイズで終幕にしましょう: SimpleHTMLブロックを「正常」に動作させるには、「熱心」なアプローチが、私たちのブロックの既存のインスタンス設定すべてのタグを取り除くことを強化する方法を探す、または、戻って、代わりに「怠惰」なアプローチを実装する必要があります (ヒント: get_content()メソッドで実行します)。

更新:

Moodle 1.5以前のバージョンでは、ファイルconfig_global.htmlには、単純にconfig.htmlというファイル名が付けられていました。また、メソッド config_saveおよび config_printは、各々handle_configおよびprint_configと名前付けられていました。ブロックがMoodle 1.5でも動作するようにするには、こられの名前付けを含めたアップグレードが必要となります。詳細は、(付録Bをご覧くださいをご覧ください。

目の保養 (Eye Candy)

私たちのブロックは、ほとんど完璧に動作するようになりました。それでは、さらに何箇所か便利にできるよう、私たちが使用できるトリックを見てみましょう。

私たちのブロックの視覚的側面を調整できる、いくつかの方法があります。まず第一に、ヘッダ (タイトル) を全く表示しないブロックを作成できると便利でしょう。あなたは、この内容をMoodleに実装されている「コース説明」ブロックで見ることができます。この動作は、あなたの予想どおり、私たちのブロッククラスに、さらに1つのメソッドを追加することで実現できます:

function hide_header() {

 return true;

}

ここでもう一つ: 私たちは、空のタイトルをブロックの init()メソッドに設定することはできません。すべてのインストール済みブロックで、Moodleが異なるタイトルを使用できるよう、 init()がコールされた後、それぞれのブロックがユニークなタイトルを持つ必要があります。

私たちが実施したい、もう一つの調整は、私たちのブロックに画面上での表示幅を教えることです。Moodleは、これを2つのプロセスで処理します: まず最初に、それぞれのブロックに推奨幅を問い合わせて、最大値を望ましい値として記憶します。それから、表示されるページが、この値を使用できるようにするか、こちらが最もあり得るのですが、推奨幅がない場合、特定の範囲の値を取得します。これは、表示幅の設定が最善努力型 (best-effort) の合意であることを意味します。あなたのブロックは、特定の表示幅を「リクエスト」することができます。Moodleは、「リクエスト」された表示幅を提供できるよう「試みます」が、結果に関して、一切保障はありません。具体的な例として、すべての標準的なMoodleコースフォーマットでは、リクエストされた表示幅を、180から210ピクセルの間で提供します。

私たちの推奨幅をブロックに教えるには、さらに1つのメソッドをブロッククラスに追加する必要があります:

function preferred_width() {

 // The preferred value is in pixels
 return 200;

}

これにより、私たちのブロック (およびページの同じ側に表示される、すべてのブロック) は、標準よりも少しだけ幅広くなります。

最後に、私たちのブロック表示に使用される、実HTMLのプロパティに影響を及ぼすことができます。それぞれのブロックは、すべて<table>エレメント内に含まれ、その中で、すべてのHTMLが表示されます。そのコンテナに特定の値を持ったHTML属性を追加するよう、私たちは、Moodleに指示することができます。これは、a) 終了結果に直接影響を及ぼす (例えば、bgcolor="black" を割り当てます)、または、b) CSSを使って、終了結果をカスタマイズする自由を私たちに与える CSS (実際のところ、これは下記のようにデフォルトで実施されます)、いずれかの方法を取ることができます。

私たちの場合、この機能のデフォルトの動作は、ブロックのコンテナに属性「sideblock block_simplehtml」(接頭辞 "block_" の次に私たちの小文字ブロック名が続きます) を持ったHTMLクラスを割り当てることです。そして、このブロックの視覚的スタイルを変更するため、そのクラスを使用して、私たちのテーマ内にCSSセレクタを作成することができます (例えば、".sideblock.block_simplehtml { border: 1px black solid}")。

デフォルトの動作を変更するには、私たちは、属性名および値の連想配列を返すメソッドを定義する必要があります。例えば、このバージョンでは、

function html_attributes() {

 return array(
   'class'       => 'sideblock block_'. $this->name(),
   'onmouseover' => "alert('Mouseover on our block!');"
 );

}

Javaスクリプトを使用したマウスオーバーイベントが、HTML内で「onmouseover="alert(...)"」と記述するのと同じように、私たちのブロックに追加されます。ここで留意すべき点は、私たちがクラス属性をセットする部分を複製することです (私たちは、この属性を保持したいと思います。また、デフォルトの動作をオーバーライドするため、必要であればエミュレートすることが、私たちの責任です)。

そして、最後にエレガントな手法は、ハードコードされた値「block_simplehtml」にクラスを設定せず、私たちのブロック名に動的に合致させるため、代わりに name()メソッドを使用することです。

認証ユーザのみ

ある状況において、ブロックが非常に有用であることを想像することは、難しいことではありません。しかし、他のユーザにとって意味あるブロックを作成することは、非常に難しいことです。この例として、ソーシャルフォーマットのコースにとって、非常に使いやすい「社会活動」ブロックがあります。しかし、このブロックは、ウィークリーフォーマットに関して、全く有用なことは実現できません。そのようなブロックは、本当に意味がある場合のみ、使用を許可するという考え方があるでしょう。そして、ブロックの使用に意味がない場合、ユーザを混乱させるべきではありません。

Moodleでは、どのコースフォーマットでブロックを表示できるか、宣言することができます。そして、ブロック開発者から設定された、この制限を常に強制することができます。この情報は、ページフォーマットに対応するキーおよび、そのページフォーマットでブロックが表示可能かどうか宣言するブール値 (true/false) の定義を持った連想配列として、Moodleに提供されます。

上の段落では、意図的に用語「コース」の代わりに「ページ」を使っていることに注意してください。この理由は、Moodle 1.5以降、ブロックは、サポートされているどのページにも表示できるからです。そのようなページの最良の例は、コースページですが、私たちは、コースページに限定するわけではありません。例えば、小テスト表示ページ (私たちが小テスト名をクリックした後、表示される最初のページ) でも、ブロックをサポートします。

私たちがページに使用できるフォーマット名は、実際にページを表示するために使用されるスクリプト名に由来します。例えば、コースでは、そのスクリプトは、/course/view.php (これは、ブラウザのアドレス行で判断できます) となります。従って、そのページのフォーマット名は、course-viewとなります。小テストビューページのフォーマット名は、mod-quiz-viewであると簡単に導くことができます。しかし、サムネイルに関するルールには、少しだけ例外があります:

  1. Moodleフロントページのフォーマット名は、site-indexです。
  2. コースのフォーマット名は、実際には、course-viewだけでなく、course-view-weekscourse-view-topics等です。
  3. そのようなページがないとしても、フォーマット名allを包括的なオプションとして使用することができます。

適用可能なフォーマット定義中で、私たちが必要なだけ、フォーマット名を含むことができます。それぞれのフォーマットを許可、不許可にすることができます。また、「このブロックは、このページで許可されますか?」という問題を解決を手助けするため、さらに3つのルールがあります:

  1. フォーマット名の接頭辞は、そのフォーマット名と合致します。例えば、modは、活動モジュールと合致します。course-viewは、コースフォーマットに関わらず、すべてのコースに合致します。そして、最後に、siteは、フロントページと合致します (フルフォーマット名は、site-indexであることを記憶してください)。
  2. 私たちのページに合致するよう、フォーマット名を特化するほど、ブロックが許可される場合の決定に関する優先度が高くなります。例えば、modmod-quizおよびmod-quiz-viewすべて、小テストのビューページに合致します。3つの名称すべてが存在する場合、合致の度合いが高いため、mod-quiz-viewが優先権を得ます。
  3. 文字 * は、言葉のどのような場所にも使うことができます。例えば、mod および mod-* は、同等です。このドキュメント執筆時点では、この「ワイルドカード合致」機能を使用する実際の理由はありませんが、将来的な利用のため存在していると考えてください。
  4. フォーマット名が表示される順番は関係ありません。

上記すべては、状況を複雑にするのに十分です。そのため、いくつかの具体例を見てみましょう。まず第一に、私たちのブロックをサイトフロントページのみに表示するため、下記の関数を使用します:

function applicable_formats() {

 return array('site' => true);

}

allが存在しないため、ブロックは「すべて」のコースフォーマットでは表示されません。しかし、siteにTRUEが設定されているため、サイトフロントページで表示されることが明確に許可されています (接頭辞により、siteは、site-indexに合致することを記憶してください)。

別の例として、ソーシャルフォーマットを除き、すべてのコースフォーマットで、ブロックを表示したい場合、また、コース以外では表示を「許可したくない」場合、私たちは次のように記述します:

function applicable_formats() {

 return array(
          'course-view' => true, 
   'course-view-social' => false);

}

今回、私たちは、すべてのコースでブロックの表示を許可して、ソーシャルフォーマットでの表示を許可しません。最後に最も複雑な例。サイトフロントページ、コース (ソーシャルコースではなく) そしてまた、小テストを除いて、すべての活動モジュールの表示時に、ブロック表示をサポートします。これは、次のようになります:

function applicable_formats() {

 return array(
          'site-index' => true,
         'course-view' => true, 
  'course-view-social' => false,
                 'mod' => true, 
            'mod-quiz' => false
 );

}

最終結果の決定に「ベストマッチ」ポリシーがあることを私たちが記憶していれば、上記目標達成を理解することは難しくありません。

UPDATING:
前のバージョン1.5では、ブロックはコース内のみで許可されていました (そして、Moodle 1.4では、サイトフロントページのみ)。その当時、有効なコースフォーマットを記述するキーワードは、若干異なっていました。また、さらにオープンアーキテクチャを許可するため、変更する必要がありました。古いブロックを新しい標準に適合させるための修正情報に関して、 Appendix Bをご覧ください。

リストおよびアイコン

このガイドの最後の部分では、私たちは、Moodleブロックの追加的な機能に関して、短く論じてみます。明確に言うと、ユーザに対して、選択可能なリストを表示するブロックを非常に簡単に作成することのできる機能です。このリストでは、1行あたり1アイテム表示されます。また、アイテムの横に任意のイメージ (アイコン) を置くことができます。このような「リストブロック」の例は、このセクションで論じるすべての点を標準的に含む、Moodle「管理」ブロックです。

今までのところ、私たちが見てきたように、ブロックは、 $this->contentに関して、次の2つのプロパティを使います:「text」および「footer」。「text」は、そのままブロックのコンテンツとして、また、「footer」は小さなサイズのフォントで、コンテンツの下に表示されます。リストブロックは、$this->content->footerを全く同じように使用しますが、$this->content->textは、無視します。

代わりにMoodleは、 get_content()がコールされる場合、そのようなブロックに次の2つのプロパティを設定することを要求します: $this->content->items および $this->content->icons です。$this->content->itemsは、表示されることになるリスト内アイテムそれぞれのHTMLを含む数値索引配列である必要があります。通常、これらのタグは、ページのリンクを提供するHTMLアンカータグです。また、$this->content->iconsも$this->content->itemsと明確に同じ数のアイテムを持った数値索引配列である必要があります。これらのアイテムは、「src」「height」「width」および「alt」属性を持った、省略なしのHTML <img>タグである必要があります。もちろん、イメージを小さく、かつ均一なサイズにすることには意味があります。

私たちが標準的なテキストブロックの代わりにリストブロックを置きたいことをMoodleに伝えるには、ブロッククラス定義を少しだけ修正する必要があります。クラスblock_baseを拡張する代わりに、私たちのブロックは、クラスblock_listを拡張します。例えば以下のようになります:

class block_my_menu extends block_list {
    // The init() method does not need to change at all
}

In addition to making this change, we must of course also modify the get_content() method to construct the $this->content variable as discussed above:


加えて,この変更をするためには,当然のことながら,上で議論した $this->content 変数を get_content() に対して修正して,変更し なくてはなりません.


function get_content() {

 if ($this->content !== null) {
   return $this->content;
 }

 $this->content         = new stdClass;
 $this->content->items  = array();
 $this->content->icons  = array();
 $this->content->footer = 'Footer here...';

 $this->content->items[] = '<a href="some_file.php">Menu Option 1</a>';
 $this->content->icons[] = '<img src="images/icons/1.gif" class="icon" alt="" />';

 // Add more list items here

 return $this->content;

}

要約すると、私たちがテキストブロックの代わりに、リストブロックを作成したい場合、ブロッククラス定義および get_content()メソッドを変更する必要があります。私たちが前述した必須の init()メソッドを追加することで、私たちの最初のリストブロックをすぐに作成することができます!

トップページに戻る

Moodle 2.0


Moodle 2.0

付録

付録は別々のページに移動されました: