Moodle 3.x Developer's Guide
上QQ阅读APP看书,第一时间看更新

An object-oriented philosophy

Object orientation is all about treating features of a system as little interconnecting black boxes. We have no idea what goes on inside a black box, but each black box can be described in three ways:

  • Each box behaves in a particular way and by making a box act out predefined, built-in behaviors, you can make it do different things
  • At any moment, a box is in a particular state
  • Every box has its own identity

Also, in fact, our little black boxes are objects and each object has a state, exhibits certain behaviors, and every object is uniquely identifiable as each has its own identity.

Objects themselves are of a particular type, called a class. Your pet cat shares some of the features of a mountain lion because they are both feline, and felines are types of mammals, so all mammals share similar characteristics, and so on. It is the same way with objects in Moodle:

If there is a specific programming task you need to perform in Moodle, you need to look for the correct API with which to carry out that task. Visit https://docs.moodle.org/dev/Core_APIs for a list of all of Moodle's internal APIs. For example, do you need to display a string on the screen? If so, use the String API. Why? It is because the String API automatically handles issues such as formatting and internationalization.

Each one of these APIs is accessed via an object. For example, use the global $DB object to access Moodle's database. This is an instance of the Data Manipulation Language (DML) API. Again and as with using the String API to display text on the screen, don't try to access the database other than through the interface Moodle provides. Why? It is because issues such as SQL injection hacks and verifying data integrity are already handled in the $DB object interface, so you don't have to worry about it.

However, what if there is a behavior that a particular interface doesn't support? This is solved by the notion of inheritance--see https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming). If, for example, the String API is missing a behavior our project requires, or we need to modify a behavior in order for it to fit our needs, we can declare a new class and base it on the String API. The new class is called a child class and the class upon which we have based the child is called the parent class. Certainly, in the case of the String API, we can reconfigure Moodle to use our new API. We will be learning how to modify an API (using the String API specifically) later in this chapter.

This section is merely a brief overview of the object-oriented philosophy, intended to be just enough of an explanation before you start Moodle plugin development. For more details on the object-oriented philosophy in general, check out the Wikipedia page on object-oriented Programming at https://en.wikipedia.org/wiki/Object-oriented_programming.