Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Tutorial: Difference between revisions

From MoodleDocs
(Added There is an [http://dev.moodle.org/course/view.php?id=2 Introduction to Moodle Programming] course at dev.moodle.org.)
(Added If you need to learn PHP, you can...)
Line 3: Line 3:
This is a tutorial to help you learn how to write plugins for Moodle from start to finish, while showing you how to navigate the most important developer documentation along the way.
This is a tutorial to help you learn how to write plugins for Moodle from start to finish, while showing you how to navigate the most important developer documentation along the way.


PRE-REQUISITES:  We assume you are fairly comfortable with [[PHP_for_novices|PHP]] in general and that you are able to install a database and web server on your local machine. There is an old [http://dev.moodle.org/course/view.php?id=2 Introduction to Moodle Programming] course at dev.moodle.org.
PRE-REQUISITES:  We assume you are fairly comfortable with [[PHP_for_novices|PHP]] in general and that you are able to install a database and web server on your local machine.  


Code examples can be found on github at https://github.com/abgreeve/devcourse where a working plugin is located.
If you need to learn PHP, you can see one PHP tutorial at http://www.w3schools.com/php/default.asp, another at http://php.net/manual/en/tutorial.php and several videos in YouTube at https://www.youtube.com/results?search_query=learn+php. There is a very old unmaintained Introduction to Moodle 1.8 Programming course at http://dev.moodle.org/course/view.php?id=2.
 
Code examples can be found on GitHub at https://github.com/abgreeve/devcourse where a working plugin is located.


==Background==
==Background==
===Setting up your development environment===
===Setting up your development environment===
* Install Git. View the link below for basic information about git and Moodle.
* Install Git. View the link below for basic information about Git and Moodle.
* Clone Moodle.
* Clone Moodle.
* Create branches and push to a public repository such as github.
* Create branches and push to a public repository such as GitHub.
====Setting up git to track your plugin====
====Setting up git to track your plugin====
Once you have Moodle cloned and installed on you machine what now? The next step is to create a repository to store your plugin.
Once you have Moodle cloned and installed on you machine what now? The next step is to create a repository to store your plugin.
# Log into your github account (https://github.com).
# Log into your GitHub account (https://github.com).
# Create a new repository. (https://help.github.com/articles/create-a-repo/)
# Create a new repository. (https://help.github.com/articles/create-a-repo/)
#* When naming your repository it is good to follow the following standard "moodle-{component}_{plugin name}" e.g. moodle-mod_newmodule (this exists - https://github.com/moodlehq/moodle-mod_newmodule)
#* When naming your repository it is good to follow the following standard "moodle-{component}_{plugin name}" e.g. moodle-mod_newmodule (this exists - https://github.com/moodlehq/moodle-mod_newmodule)

Revision as of 17:00, 11 September 2016

Welcome to Moodle development!

This is a tutorial to help you learn how to write plugins for Moodle from start to finish, while showing you how to navigate the most important developer documentation along the way.

PRE-REQUISITES: We assume you are fairly comfortable with PHP in general and that you are able to install a database and web server on your local machine.

If you need to learn PHP, you can see one PHP tutorial at http://www.w3schools.com/php/default.asp, another at http://php.net/manual/en/tutorial.php and several videos in YouTube at https://www.youtube.com/results?search_query=learn+php. There is a very old unmaintained Introduction to Moodle 1.8 Programming course at http://dev.moodle.org/course/view.php?id=2.

Code examples can be found on GitHub at https://github.com/abgreeve/devcourse where a working plugin is located.

Background

Setting up your development environment

  • Install Git. View the link below for basic information about Git and Moodle.
  • Clone Moodle.
  • Create branches and push to a public repository such as GitHub.

Setting up git to track your plugin

Once you have Moodle cloned and installed on you machine what now? The next step is to create a repository to store your plugin.

  1. Log into your GitHub account (https://github.com).
  2. Create a new repository. (https://help.github.com/articles/create-a-repo/)
  3. Set up git to upload to this repository.
    1. Create the directory that contains your plugin (if we were creating the plugin above, we would create a directory called "newmodule").
    2. Initialise git git init.
    3. Set the remote to push changes to git remote add origin https://github.com/{your github user name}/{repository name}. The "origin" part is the name given for the remote name and can be changed to anything else such as "upstream".

Creating your first commit

At the moment you are on a master branch. Creating a branch is a good idea so that you can try out ideas and when you are satisfied with your code merge the branch into master.

  1. Create a new branch git checkout -b {name of the branch} The name of the branch is up to you. Something descriptive is recommended.
  2. When you are happy with you branch and want to upload your code to the repository you can merge the branch with master. git merge {branch name}Now to send the new master branch to the repository. git push origin master

You code is now uploaded to your repository on github and others can now easily download and contribute to your code.

links

The Moodle development framework

What type of plugin are you developing?

  • Moodle has lots of different types of plugins.
  • There are 24 different categories of plugin listed on the moodle plugin database. Before starting check here to see if someone else has not already created what you are looking for. Perhaps you could contribute to their plugin instead of creating a new one.

links

Let's make a plugin

The skeleton of your plugin

plugin-skeleton.png

This image shows directories and files that you will find in most plugins.

  • plugin would actually be the name of your plugin. This also applies to the file in "lang/en/".
  • classes contains classes used in your plugin.
  • db has database related files and also capabilities (access.php).
  • lang The language directory.
  • lib.php base library file for some hooks and callbacks.
  • version.php contains bare basic information about the plugin.

links

Basic page structure

  • For a page that is displaying content to a user we have the following sections:
    • Required files.
    • POST and GET variables retrieved using required_param and optional_param.
    • context.
    • navigation setup.
    • title, headings, headers.
    • content.
    • footers.

// Required files. require_once(__DIR__ . '/config.php'); // Required and optional parameters. $id = required_param('id', PARAM_INT); $text = optional_param('text', , PARAM_ALPHA);

// Setting context for the page. $PAGE->set_context(context_system::instance()); // URL is created and then set for the page navigation. $url = new moodle_url('/test.php'); $PAGE->set_url($url); // Heading, headers, page layout. $PAGE->set_heading(get_string('hello')); $PAGE->set_pagelayout('standard'); echo $OUTPUT->header(); // Displaying basic content. echo html_writer::tag('p', $text); // Display the footer. echo $OUTPUT->footer();

links

How to support over 100 languages

  • Language files are stored in the "lang" directory. English strings would be found in "lang/en". Each language contains a file named after the plugin which contains all of the strings. For example the language strings for the assignment activity are found in "mod/assign/lang/en/assign.php".
  • Moodle's default is Australian English.
    • American English is a separate language pack (en_us). Please use only Autralian (UK) English grammar and spelling when writing Moodle plugins.
    • There is no need to include languages other than the default English, as almost all approved plugin strings will be automatically imported into AMOS for translation by the language packs translators.
  • get_string() is used in most cases for displaying text.
  • lang_string() is used in situations where the text may not necessarily be displayed.

// Declaration in language file (lang/en/{pluginname}.php) $string['nameofstring'] = 'Actual string';

The get_string() function takes four parameters, but in this example we are only filling in the first two. The last two parameters are optional. The first parameter is the identifier for the string. The second is the component. The component will be the name of the language file. The following example shows a string in the badges block. // Use of string in code. echo html_writer::tag('p', get_string('numbadgestodisplay', 'block_badges'));


links

Add content to your page

  • Content for a page is added through renderers.
  • Renderers are typically stored in the "classes/output" directory.
  • Putting content in renderers allows themers to override the visual display of the content.
  • Very basic information is presented using the html_writer class.
  • In most cases templates should be used.
  • templates are stored in the "templates" directory. The templates use mustache files.
  • Mustache files allow for more generic html with placeholders inserted, that inserts the data (context) at run time.

The example used below is an admin tool and would be located under admin/tool.

Step One: Create a class for rendering. This class collects information to display and has a method for formatting that information into a format that the template will understand.

devcourse/classes/output/developer_course_main_page.php

namespace tool_devcourse\output; defined('MOODLE_INTERNAL') || die();

use renderable; use renderer_base; use templatable; use stdClass;


class developer_course_main_page implements renderable, templatable {

  protected $comment;
   /**
    * Construct this renderable.
    * @param int $courseid The course record for this page.
    */
   public function __construct($comment) {
       $this->comment = $comment;
   }
   /**
    * Export this data so it can be used as the context for a mustache template.
    *
    * @param renderer_base $output Renderer base.
    * @return stdClass
    */
   public function export_for_template(renderer_base $output) {
       $data = new stdClass();
       $data->comment = $this->comment;
       return $data;
   }

}


Step Two: To render this information a custom renderer is created for the plugin. This renderer class must extend plugin_renderer_base.

devcourse/classes/output/renderer.php

namespace tool_devcourse\output;

defined('MOODLE_INTERNAL') || die();

use plugin_renderer_base; use renderable;

class renderer extends plugin_renderer_base {

    /**
    * Defer to template.
    *
    * @param developer_course_main_page $page
    *
    * @return string html for the page
    */
   public function render_developer_course_main_page(developer_course_main_page $page) {
       $data = $page->export_for_template($this);
       return parent::render_from_template('tool_devcourse/developer_course_main_page', $data);
   }

}


Step three: A mustache template is to then be created. The information is sent to the template and at this point the information is known as the context (not to be confused with the normal definition of context throughout Moodle).

devcourse/templates/developer_course_main_page.mustache {{!

   @template tool_devcourse/developer_course_main_page
   Example context (json):
   {
       "comment": "Example comment for the context"
   }

}}

{{#str}}maintitle, tool_devdocTemplate:/str

This shows an extremely simple mustache template with one item in the context (comment). It also shows how strings are defined in the template.

Step four: To actually have this template be displayed we get the custom renderer. This chunk of code would be located in a place such as devcourse/index.php after the appropriate setup outlined in the basic page structure. $output = $PAGE->get_renderer('tool_devcourse'); //Then we get the class for rendering and provide it with information (if needed). $randomcomment = 'This comment is random'; $page = new \tool_devdoc\output\developer_course_main_page($randomcomment); //Finally we echo out the template echo $output->render($page);

links

Adding your plugin into Moodle's navigation

  • The moodle navigation system has hooks which allows plugins to add links to the navigation menu.
  • Hooks are located in lib.php. Try to keep lib.php as small as possible as this file is included on every page. Put classes and functions elsewhere.
  • Course navigation extension example:

function tool_devcourse_extend_navigation_course($navigation, $course, $coursecontext) {

   $url = new moodle_url('/admin/tool/devcourse/index.php');
   $devcoursenode = navigation_node::create('Development course', $url, navigation_node::TYPE_CUSTOM, 'Dev course', 'devcourse');
   $navigation->add_node($devcoursenode);

}

links

Database queries

  • Moodle has a generic database query library. Behind this library are additional libraries which allow Moodle to work with MySQL, PostgreSQL, Oracle, SQL Server, and Maria DB.
  • Where possible it is advisable to use the predefined functions rather than write out SQL. Writing SQL has a greater chance of not working with one of the supported databases.
  • The return of the select functions tends to be an object or an array of objects.

Example call to retrieve data from the course table. $courses = $DB->get_records('course', null, , 'id, category, fullname, shortname'); Example of data returned from the above code. Array (

   [43] => stdClass Object
       (
           [id] => 43
           [category] => 1
           [fullname] => XX -Test 5
           [shortname] => xxt5
       )
   [5] => stdClass Object
       (
           [id] => 5
           [category] => 1
           [fullname] => With the glossary
           [shortname] => wtg
       )
   [39] => stdClass Object
       (
           [id] => 39
           [category] => 1
           [fullname] => XX - Test 1
           [shortname] => xxt1
       )

)

links

Creating your own database tables

  • We create our database tables in Moodle using the XMLDB editor. This is located in the administration block "Site administration | Development | XMLDB editor".
  • The {plugin}\db directory needs to have write access for the XMLDB editor to be most effective.
  • XMLDB editor creates an install.xml file in the db directory. This file will be loaded during the install to create your tables.
  • XMLDB editor will produce php update code for adding and updating moodle database tables.

The XMLDB main page.

xmldb-main.png

Upgrade code generated by the XMLDB

xmldb-upgrade-code.png

links

Supporting access permissions: roles, capabilities and contexts

  • Capabilities are controlled in "access.php" under the "db" directory.
  • This file has an array of capabilities with the following:
    • name
    • possible security risks behind giving this capability.
    • The context that this capability works in.
    • The default roles (teacher, manager, student, etc) that have this capability.
    • Various other information.
  • These capabilities are checked in code to allow access to pages, sections, and abilities (saving, deleting, etc).

links

Adding web forms

  • Moodle has it's own forms library.
  • The forms lib includes a lot of accessibility code, and error checking, by default.
  • Moodle forms can be displayed in JavaScript using 'fragments'.

links

Maintaining good security

  • Use the sesskey when directing to pages to do actions.
  • Use the appropriate filters when retrieving parameters

links

Handling files

  • Files are conceptually stored in file areas.
  • Plugins can only access files from it's own component.

links

Adding Javascript

  • Moodle is currently using jquery and AMD (Asynchronous Module Definition).
  • JavaScript files are located in the "amd/src" directory.
  • Use grunt to build your JavaScript.
  • Include your JavaScript in php files as follows:

$this->page->requires->js_call_amd('{JScriptfilename}');

  • Can also be included in mustache templates.

links

Adding events and logging

  • All logging in moodle is done through the events system.
  • New events should be located in the "classes/event" directory.
  • It is possible to create observers and subscribe to events.

links

Web Services and AJAX

  • Moodle web services uses the external functions API.
  • The recommended way to make AJAX requests is to use the ajax AMD file which uses the external functions API.
  • External functions should be located in the "classes/external.php" file.
  • A list of services should be included in "db/services.php". This file is required to register the web services with Moodle.
  • The services list is an array which contains:
    • classname Name of the external class.
    • methodname The name of the external function.
    • classpath system path to the external function file.
    • description Description of the function
    • type Create, read, update, delete
    • ajax Can this function be used with ajax?
    • capabilities Capabilities required to use this function.

links

Using caching to improve performance

  • The main cache used by moodle is the Moodle Universal Cache (MUC).
  • The MUC has several cache definitions -
    • Request cache
    • Session cache
    • Application

links

Supporting backup and restore

  • Supporting backup and restore requires creating several files in the 'backup/moodle2' directory.
  • Back requires a class to extend the backup_task of some sort. There may be a specific plugin task to extend.
  • Restore requires a class to extend the restore_task of some sort. There may be a specific plugin task to extend.
  • The restore steps lib defines the structure of the plugin to be restored.
  • The backup steps lib defines steps, settings, attributes, etc.

links

Supporting automated testing

  • Moodle has two types of automated testing: php unit tests, and behat tests.
  • Unit tests are for testing functions.
  • Behat tests runs through scenarios.
    • Behat tests follows a script and navigates through moodle pages.
  • unit tests should be located in the "tests" directory.
  • behat tests should be located in the "tests/behat" directory.
  • Tests located in these directories will be run through when a full test run is initiated.
  • behat tests are actually feature files and end with the extension ".feature".

links

Publishing your plugin

Adding your plugin to moodle.org

  • publish your plugins at https://moodle.org/plugins/
  • Publishing plugins on the moodle site leads you through a bunch of steps that need to be completed in order for the plugin to be approved and published.
  • Plugins will be run through a pre-checker to give suggestions about possible issues with the code.

Supporting your plugin

TODO

Finishing this tutorial:

  1. About one or two screens for each section with a very generic overview for beginners, containing links to relevant docs WITH COMMENTS ABOUT QUALITY, USEFULNESS, CAVEATS etc.
  2. Go through all the linked pages and make sure they are current and accurate.
  3. Add a worked example to this page, so that each section has suggestions about things to add to the admin tool being built as an exercise. If the code is long, it could be placed on separate pages. A good reference for style is Moodle_Mobile_Developing_a_plugin_tutorial and Blocks.

See also these older tutorials