「開発:ブロック/付録A」の版間の差分

提供:MoodleDocs
移動先:案内検索
115行目: 115行目:


'''または'''<br />
'''または'''<br />
あなたのブロックが'''block_list'''から派生している場合、$this->content->items、$this->content->iconsおよび$this->content->footerを定義します。The first two should be numerically indexed arrays having the exact same number of elements. $this->content->items is an array of strings that can contain arbitrary HTML while $this->content->icons also contains should strings, but those must be fully-qualified HTML <img> tags '''and nothing else'''. $this->content->footer is a string, as above.
あなたのブロックが'''block_list'''から派生している場合、$this->content->items、$this->content->iconsおよび$this->content->footerを定義します。最初の2つは、正確にエレメントの番号を持った、数字インデックス付きの配列です。$this->content->items is an array of strings that can contain arbitrary HTML while $this->content->icons also contains should strings, but those must be fully-qualified HTML <img> tags '''and nothing else'''. $this->content->footer is a string, as above.
<br />'''を意味します。'''
<br />'''を意味します。'''



2009年6月28日 (日) 15:49時点における版

作成中です - Mitsuhiro Yoshida 2009年5月26日 (火) 15:50 (UTC)

付録A: block_base 参照

この付録では、他のすべてのブロッククラスが導き、渡し、そしてすべてのメソッドが開発者により詳細にオーバーライドすることのできる、ベースクラスblock_baseに関して説明します。オーバーライドすべきではないメソッドに関しては、明確に言及します。この別表を読んだ後、ブロック機能実装に関して、あなたがオーバーライドすべき、またはオーバーライドできる、すべてのメソッドを明確に理解できます。

メソッドは、3つのカテゴリに分けられます: 「あなたのブロックで使用およびオーバーライドするメソッド」、「あなたにはオーバーライドできませんが、使用したいメソッド」、「使用およびオーバーライドできない内部メソッド」です。それぞれのカテゴリでは、メソッドをアルファベット順に表示します。

あなたが自由に使用およびオーバーライドできるメソッド:

after_install()

function after_install() { }

Moodle 1.7またはそれ以降のバージョンで利用可

このメソッドは、ブロックサブクラスからオーバーライドされるため、またブロックのインストール後、あなたが特定のタスクを指定できるよう、デザインされました。例えば、ブロックのインストール後、あなたはデータを保存したいと考えるでしょう。しかしながら、それぞれのデータベースタイプは、現在の日付を取得する独自の方法を持っています。また、あなたのブロックインストール時、XMLDBを使用しますが、これらの処理も同様にサポートされていません。データベースアブストラクションのメンテナンス時、そのようなタスクを完了するためのベストな方法は、ブロックインストールにXMLDBを使用した後、ブロック使用前のデータ挿入にafter_install() メソッドを使用することです。

after_install() は、ブロックごとに1回のみコールされ、インスタンスごとにコールされるわけではないことに留意してください。

applicable_formats()

function applicable_formats() {

 // デフォルトのケース: ブロックはコースおよびサイトインデックスで使用できますが、活動では使用できません。
 return array('all' => true, 'mod' => false);

}

Moodle 1.5またはそれ以降のバージョンで利用可

このメソッドでは、どのページにブロックを追加することができるか、あなたがコントロールできます。ページフォーマットは、そのページを表示されるために使用されるスクリプトのフルパスにより構成されます。あなたは、ページフォーマット名およびブール値 (trueまたはfalse) のキーを含む配列を戻す必要があります。あなたのブロックは、値が「true」の場合のみ、それらのフォーマットで表示することができます。 フォーマット名のサンプルは次のとおりです: course-viewsite-index (これは例外です。Moodleサイトのフロントページを参照します)、course-format-weeks (特定のコースフォーマットを参照します)、mod-quiz (小テストモジュールを参照します)、all (あなたが明確に許可または許可しない場合に使用されます)。

完全に合致するルールは、以下のとおりです:

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

before_delete()

function before_delete() { }

Moodle 1.7またはそれ以降のバージョンで利用可

このメソッドは、管理者がMoodleからブロックを削除した時点でコールされます。また、直前に関連するデータベーステーブルも削除されます。ブロックの作者は、一時ファイルの削除等、ブロックが削除される前に、必要なクリーンアップを実施することができます。

config_print()

function config_print() {

 // Default behavior: print the config_global.html file
 // You don't need to override this if you're satisfied with the above
 if (!$this->has_config()) {
   return FALSE;
 }
 global $CFG, $THEME;
 
 print_simple_box_start('center', , $THEME->cellheading);
 include($CFG->dirroot.'/blocks/'. $this->name() .'/config_global.html');
 print_simple_box_end();
 return TRUE;

}

Moodle 1.5またはそれ以降のバージョンで利用可

このメソッドでは、あなたのブロックでグローバル設定画面がどのように表示されるか選択することができます。これは、「設定 ...」を使って特定のブロックの選択時、管理者に表示される画面です。あなたがデフォルトの実装をさらに複雑にしたい場合、オーバーライドしてください。しかし、以下の点に留意してください:

  • あなたが設定オプションを$CFGに保存している場合、あらゆるHTML設定画面をインクルードする前に、恐らく「global $CFG;」を使用する必要があります。
  • あなたのメソッドのアウトプットに含まれているHTML<input>要素は、自動的に<form>エレメントで囲まれます。あなたは、どこで、どのようにformが送信されるか心配する必要はありません。しかし、あなたは送信する方法を提供しなければなりません (例 <input type="submit" />)。メソッドの動作の成功または失敗を示すため、あなたはブール値を返す必要があります。

config_save()

function config_save($data) {

 // Default behaviour: save all variables as $CFG properties
 // You don't need to override this if you 're satisfied with the above
 foreach ($data as $name => $value) {
   set_config($name, $value);
 }
 return TRUE;

}

Moodle 1.5またはそれ以降のバージョンで利用可

このメソッドでは、あなたのグローバル設定データのストレージメカニズムをオーバーライドすることができます。受け取る変数は、キーにnames、値にvaluesが設定されている連想配列です。デフォルトの実装では、すべてをMoodle $CFGの値として保存します。処理するためにMoodleが、いくつかの隠しフィールドをフォームに追加するため、$dataは、送信されたPOSTデータすべてを保持するわけではないことに留意してください。しかし、このメソッドをコールする前、受信されたデータより隠しフィールドは取り除かれます。そのため、このメソッドがコールされた場合、「実」設定データのみが残ります。

メソッドの動作の成功または失敗を示すため、あなたはブール値を返す必要があります。

get_content()

function get_content() {

 // This should be implemented by the derived class.
 return NULL;

}

Moodle 1.5またはそれ以降のバージョンで利用可

コールされる場合、このメソッドでは、あなたのブロックの$this->content変数を投入すべきです。変数の投入は下記を意味します:

以下の内容
あなたのブロックがblock_baseから派生している場合、$this->content->text および $this->content->footer を定義します。両方ともストリングにすべきであり、任意のHTMLを含むことができます。

または
あなたのブロックがblock_listから派生している場合、$this->content->items、$this->content->iconsおよび$this->content->footerを定義します。最初の2つは、正確にエレメントの番号を持った、数字インデックス付きの配列です。$this->content->items is an array of strings that can contain arbitrary HTML while $this->content->icons also contains should strings, but those must be fully-qualified HTML <img> tags and nothing else. $this->content->footer is a string, as above.
を意味します。

If you set all of these variables to their default "empty" values (empty arrays for the arrays and empty strings for the strings), the block will not be displayed at all except to editing users. This is a good way of having your block hide itself to unclutter the screen if there is no reason to have it displayed.

Before starting to populate $this->content, you should also include a simple caching check. If $this->content is exactly equal to NULL then proceed as normally, while if it is not, return the existing value instead of calculating it once more. If you fail to do this, Moodle will suffer a performance hit.

In any case, your method should return the fully constructed $this->content variable.

has_config()

function has_config() {

 return FALSE;

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method should return a boolean value that denotes whether your block wants to present a configuration interface to site admins or not. The configuration that this interface offers will impact all instances of the block equally. To actually implement the configuration interface, you will either need to rely on the default config_print method or override it. The full guide contains more information on this.

hide_header()

function hide_header() {

 //Default, false--> the header is shown
 return FALSE;

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method should return a boolean value that denotes whether your block wants to hide its header (or title). Thus, if you override it to return true, your block will not display a title unless the current user is in editing mode.

html_attributes()

function html_attributes() {

 // Default case: an id with the instance and a class with our name in it
 return array('id' => 'inst'.$this->instance->id, 'class' => 'block_'. $this->name());

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method should return an associative array of HTML attributes that will be given to your block's container element when Moodle constructs the output HTML. No sanitization will be performed in these elements at all.

If you intend to override this method, you should return the default attributes as well as those you add yourself. The recommended way to do this is:

function html_attributes() {

 $attrs = parent::html_attributes();
 // Add your own attributes here, e.g.
 // $attrs['width'] = '50%';
 return $attrs;

}

init()

function init() {

 $this->title = get_string('simplehtml', 'block_simplehtml');
 $this->version = 2004111200;

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method must be implemented for all blocks. It has to assign meaningful values to the object variables $this->title and $this->version (which is used by Moodle for performing automatic updates when available).

No return value is expected from this method.

instance_allow_config()

function instance_allow_config() {

 return FALSE;

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method should return a boolean value. True indicates that your block wants to have per-instance configuration, while false means it does not. If you do want to implement instance configuration, you will need to take some additional steps apart from overriding this method; refer to the full guide for more information.

This method's return value is irrelevant if instance_allow_multiple returns true; it is assumed that if you want multiple instances then each instance needs its own configuration.

instance_allow_multiple()

function instance_allow_multiple() {

 // Are you going to allow multiple instances of each block?
 // If yes, then it is assumed that the block WILL USE per-instance configuration
 return FALSE;

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method should return a boolean value, indicating whether you want to allow multiple instances of this block in the same page or not. If you do allow multiple instances, it is assumed that you will also be providing per-instance configuration for the block. Thus, you will need to take some additional steps apart from overriding this method; refer to the full guide for more information.

instance_config_print()

function instance_config_print() {

 // Default behavior: print the config_instance.html file
 // You don't need to override this if you're satisfied with the above
 if (!$this->instance_allow_multiple() && !$this->instance_allow_config()) {
   return FALSE;
 }
 global $CFG, $THEME;

 if (is_file($CFG->dirroot .'/blocks/'. $this->name() .'/config_instance.html')) {
   print_simple_box_start('center', , $THEME->cellheading);
   include($CFG->dirroot .'/blocks/'. $this->name() .'/config_instance.html');
   print_simple_box_end();
  } else {
    notice(get_string('blockconfigbad'),
       str_replace('blockaction=', 'dummy=', qualified_me()));
  }
  return TRUE;

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method allows you to choose how to display the instance configuration screen for your block. Override it if you need something much more complex than the default implementation allows you to do. Keep in mind that whatever you do output from config_print, it will be enclosed in a HTML form automatically. You only need to provide a way to submit that form.

You should return a boolean value denoting the success or failure of your method's actions.

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

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method allows you to override the storage mechanism for your instance configuration data. The received argument is an associative array, with the keys being setting names and the values being setting values.

The configuration must be stored in the "configdata" field of your instance record in the database so that Moodle can auto-load it when your block is constructed. However, you may still want to override this method if you need to take some additional action apart from saving the data. In that case, you really should do what data processing you want and then call parent::instance_config_save($data) with your new $data array. This will keep your block from becoming broken if the default implementation of instance_config_save changes in the future.

Note that $data does not hold all of the submitted POST data because Moodle adds some hidden fields to the form in order to be able to process it. However, before calling this method it strips the hidden fields from the received data and so when this method is called only the "real" configuration data remain.

If you want to update the stored copy of the configuration data at run time (for example to persist some changes you made programmatically), you should not use this method. The correct procedure for that purpose is to call instance_config_commit.

You should return a boolean value denoting the success or failure of your method's actions.

preferred_width()

function preferred_width() {

 // Default case: the block wants to be 180 pixels wide
 return 180;

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method should return an integer value, which is the number of pixels of width your block wants to take up when displayed. Moodle will try to honor your request, but this is actually up to the implementation of the format of the page your block is being displayed in and therefore no guarantee is given. You might get exactly what you want or any other width the format decides to give you, although obviously an effort to accomodate your block will be made.

Most display logic at this point allocates the maximum width requested by the blocks that are going to be displayed, bounding it both downwards and upwards to avoid having a bad-behaving block break the format.

refresh_content()

function refresh_content() {

 // Nothing special here, depends on content()
 $this->content = NULL;
 return $this->get_content();

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method should cause your block to recalculate its content immediately. If you follow the guidelines for get_content, which say to respect the current content value unless it is NULL, then the default implementation will do the job just fine. You should return the new value of $this->content after refreshing it.

specialization()

function specialization() {

 // Just to make sure that this method exists.

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method is automatically called by the framework immediately after your instance data (which includes the page type and id and all instance configuration data) is loaded from the database. If there is some action that you need to take as soon as this data becomes available and which cannot be taken earlier, you should override this method.

The instance data will be available in the variables $this->instance and $this->config.

This method should not return anything at all.

Methods which you should not override but may want to use:

get_content_type()

function get_content_type() {

 return $this->content_type;

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method returns the value of $this->content_type, and is the preferred way of accessing that variable. It is guaranteed to always work, now and forever. Directly accessing the variable is not recommended; future library changes may break compatibility with code that does so.

get_title()

function get_title() {

 return $this->title;

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method returns the value of $this->title, and is the preferred way of accessing that variable. It is guaranteed to always work, now and forever. Directly accessing the variable is not recommended; future library changes may break compatibility with code that does so.

get_version()

function get_version() {

 return $this->version;

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method returns the value of $this->version, and is the preferred way of accessing that variable. It is guaranteed to always work, now and forever. Directly accessing the variable is not recommended; future library changes may break compatibility with code that does so.

instance_config_commit()

function instance_config_commit() {

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

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method saves the current contents of $this->config to the database. If you need to make a change to the configuration settings of a block instance at run time (and not through the usual avenue of letting the user change it), just make the changes you want to $this->config and then call this method.

is_empty()

For blocks that extend class block_base:

function is_empty() {

 $this->get_content();
 return(empty($this->content->text) && empty($this->content->footer));

}

Moodle 1.5またはそれ以降のバージョンで利用可

For blocks that extend class block_list:

function is_empty() {

 $this->get_content();
 return (empty($this->content->items) && empty($this->content->footer));

}

This method returns the a boolean true/false value, depending on whether the block has any content at all to display. Blocks without content are not displayed by the framework.

name()

function name() {

 static $myname;
 if ($myname === NULL) {
   $myname = strtolower(get_class($this));
   $myname = substr($myname, strpos($myname, '_') + 1);
 }
 return $myname;

}

Moodle 1.5またはそれ以降のバージョンで利用可

This method returns the internal name of your block inside Moodle, without the block_ prefix. Obtaining the name of a block object is sometimes useful because it can be used to write code that is agnostic to the actual block's name (and thus more generic and reusable). For an example of this technique, see the config_print method.

Methods which you should not override and not use at all:

_add_edit_controls()

This is a private method; no description is given.

_load_instance()

This is a private method; no description is given.

_print_block()

This is a private method; no description is given.

_print_shadow()

This is a private method; no description is given.

_self_test()

This is a private method; no description is given.

The class block_base also has a few standard member variables which its methods manipulate. These variables, the purpose of each and the type of data they are expected to hold is explained in the next section of this Appendix.

Class variables:

$this->config

This variable holds all the specialized instance configuration data that have been provided for this specific block instance (object). It is an object of type stdClass, with member variables directly corresponding to the HTML <input> elements in the block's config_instance.html file.

The variable is initialized just after the block object is constructed, immediately before specialization is called for the object. It is possible that the block has no instance configuration, in which case the variable will be NULL.

It is obvious that there is a direct relationship between this variable and the configdata field in the mdl_block_instance table. However, it is strongly advised that you refrain from accessing the configdata field yourself. If you absolutely must update its value at any time, it is recommended that you call the method instance_config_commit to do the actual work.

$this->content

This variable holds all the actual content that is displayed inside each block. Valid values for it are either NULL or an object of class stdClass, which must have specific member variables set as explained below. Normally, it begins life with a value of NULL and it becomes fully constructed (i.e., an object) when get_content is called.

After it is fully constructed, this object is expected to have certain properties, depending on the value of $this->content_type.

Specifically:

  1. text This is a string of arbitrary length and content. It is displayed inside the main area of the block, and can contain HTML.
  2. footer This is a string of arbitrary length and contents. It is displayed below the text, using a smaller font size. It can also contain HTML.
  1. items This is a numerically indexed array of strings which holds the title for each item in the list that will be displayed in the block's area. Since usually such lists function like menus, the title for each item is normally a fully qualified HTML <a> tag.
  2. icons This is a numerically indexed array of strings which represent the images displayed before each item of the list. It therefore follows that it should have the exact number of elements as the items member variable. Each item in this array should be a fully qualified HTML <img> tag.
  3. footer This is a string of arbitrary length and contents. It is displayed below the text, using a smaller font size. It can also contain HTML.

$this->content_type

This variable instructs Moodle on what type of content it should assume the block has, and is used to differentiate text blocks from list blocks. It is essential that it has a meaningful value, as Moodle depends on this for correctly displaying the block on screen. Consequently, this variable is closely tied with the variable $this->content. The variable is expected to have a valid value after the framework calls the init method for each block.

The only valid values for this variable are the two named constants BLOCK_TYPE_TEXT and BLOCK_TYPE_LIST.

$this->instance

This member variable holds all the specific information that differentiates one block instance (i.e., the PHP object that embodies it) from another. It is an object of type stdClass retrieved by calling get_record on the table mdl_block_instance. Its member variables, then, directly correspond to the fields of that table. It is initialized immediately after the block object itself is constructed.

$this->title

This variable is a string that contains the human-readable name of the block. It is used to refer to blocks of that type throughout Moodle, for example in the administrator's block configuration screen and in the editing teacher's add block menu. It is also the title that is printed when the block is displayed on screen, although blocks can specifically change this title to something else if they wish (see below). The variable is expected to have a valid value after the framework calls the init method for each object.

In the case of blocks which may want to configure their title dynamically through instance configuration, it is still essential to provide a valid title inside init. This title may then be overridden when the specialization method is called by the framework:

function specialization() {

 // At this point, $this->instance and $this->config are available
 // for use. We can now change the title to whatever we want.
 $this->title = $this->config->variable_holding_the_title;

}

A lot of blocks seem to use

$this->title = get_string('blockname', ... );

to set the title of the block (and then put a more specific title inside the language file).

If there is no proper language string, the title of the block will then be set to blockname. If there is another block with the same generic title, then an error will show up: Naming conflict.

To avoid this error on installations with missing language strings, use a more specific name when calling the language string...

$this->title = get_string('simplehtml', ... );

That way all blocks will show up with a unique title in the admin area, even if people have not yet succeeded in placing language files in the correct location

$this->version

This variable should hold each block's version number in the form YYYYMMDDXX, as per the convention throughout Moodle. The version number is used by Moodle to detect when a block has been upgraded and it consequently needs to run the block's upgrade code to bring the "old" version of the block's data up to date. The variable is expected to have a valid value after the framework calls the init method for each block.

Most blocks do not keep complex data of their own in the database the way that modules do, so in most cases nothing actually happens during a block version upgrade. However, the version number is displayed in the administration interface for blocks. It is good practice therefore to change your block's version number when it gains new functionality or receives important bug fixes, to enable site administrators to easily identify the exact version of the block they are working with.

Appearing throughout the code related to the Blocks API, there is a number of predefined constants that are utilized to avoid the use of "magic numbers" in the code. These constants are:

Named constants:

BLOCK_TYPE_LIST

This is one of the two valid values for the $this->content_type member variable of every block. Its value specifies the exact requirements that Moodle will then have for $this->content.

BLOCK_TYPE_TEXT

This is one of the two valid values for the $this->content_type member variable of every block. Its value specifies the exact requirements that Moodle will then have for $this->content.