官术网_书友最值得收藏!

Creating a block from scratch

We will start our exploration of block plugins by revisiting a programming classic, Hello World. Our first block will be about as simple a block as possible, simply displaying the text Hello World.

Because our block will be called Hello World, let's start by creating a folder in the block folder of our development site called helloworld. Inside of this folder, create an empty PHP file called block_helloworld.php. Note that the pattern is module-type_module-name.php.

We start by creating a new class block_helloworld that extends the block_base class. Then we create a new init function for this class. We set the two required values: the block title and the block version, as follows:

<?php
class block_helloworld extends block_base {
function init() {
$this->title = get_string('helloworld', 'block_helloworld');
$this->version = 2009050700;
}//function init

Assigning content to our block

Once we have created the init() function, all that is left in order to have a functioning block is to assign some content to our block for display in the get_content() function. Block content is stored in $this->content:

function get_content() {
if ($this->content !== NULL) {
return $this->content;
}//if
$this->content = new stdClass;
$this->content->text = 'Hello World!';
return $this->content;
}//function get_content
}//class block_helloworld
?>

Now try out the results of our new code, by logging into Moodle with an administrator account. Click on the Notifications link in the Site Administration block. Moodle then notifies us that it has installed the [[helloworld]] block.

Now let's turn on editing, and from the drop-down list of blocks we will see our new block [[helloworld]] at the bottom of the list. We then click on it to add an instance of the block to our current page. The results will look similar to the following screenshot:

Assigning content to our block
主站蜘蛛池模板: 五华县| 诸暨市| 汶上县| 太白县| 凌海市| 抚松县| 惠水县| 邵东县| 常州市| 鞍山市| 安阳市| 富蕴县| 洛宁县| 东丽区| 息烽县| 漳平市| 玉屏| 富平县| 新田县| 呼伦贝尔市| 顺平县| 嘉善县| 儋州市| 拜城县| 东乌珠穆沁旗| 钦州市| 策勒县| 肇州县| 上林县| 屏东市| 丹东市| 金山区| 江津市| 通江县| 县级市| 凌云县| 芮城县| 亳州市| 连平县| 茂名市| 北碚区|