Skip to content

Commit 72e0ce7

Browse files
committed
[docs] Add \core\formatting and DI docs for MDL-80072
1 parent eb7ffb3 commit 72e0ce7

File tree

3 files changed

+349
-16
lines changed

3 files changed

+349
-16
lines changed

docs/apis/core/di/index.md

+202
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
---
2+
title: Dependency Injection
3+
tags:
4+
- DI
5+
- Container
6+
- PSR-11
7+
- PSR
8+
description: The use of PSR-11 compatible Dependency Injection in Moodle
9+
---
10+
11+
import {
12+
Since,
13+
ValidExample,
14+
InvalidExample,
15+
Tabs,
16+
TabItem,
17+
} from '@site/src/components';
18+
19+
<Since version="4.4" issueNumber="MDL-80072" />
20+
21+
Moodle supports the use of [PSR-11](https://www.php-fig.org/psr/psr-11/) compatible Dependency Injection, accessed using the `\core\di` class, which internally makes use of [PHP-DI](https://php-di.org). All usage should be through the `\core\di` class.
22+
23+
Most class instances can be fetched using their class name without any manual configuration. Support for configuration of constructor arguments is also possible, but is generally discouraged.
24+
25+
Dependencies are stored using a string id attribute, which is typically the class or interface name of the dependency. Use of other arbitrary id values is strongly discouraged.
26+
27+
## Fetching dependencies
28+
29+
Moodle provides a wrapper around the PSR-11 Container implementation which should be used to fetch dependencies:
30+
31+
```php title="Fetching an instance of the \core\http_client class"
32+
$client = \core\di::get(\core\http_client::class);
33+
```
34+
35+
## Configuring dependencies
36+
37+
In some rare cases you may need to supply additional configuration for a dependency to work properly. This is usually in the case of legacy code, and can be achieved with the `\core\hook\di_configuration` hook.
38+
39+
<Tabs>
40+
41+
<TabItem value="config" label="Hook configuration">
42+
43+
The callback must be linked to the hook by specifying a callback in the plugin's `hooks.php` file:
44+
45+
```php title="mod/example/db/hooks.php"
46+
<?php
47+
$callbacks = [
48+
[
49+
'hook' => \core\hook\di_configuration::class,
50+
'callback' => \mod_example\hook_listener::class . '::inject_dependenices',
51+
],
52+
];
53+
```
54+
55+
</TabItem>
56+
57+
<TabItem value="hook" label="Hook listener">
58+
59+
The hook listener consists of a static method on a class.
60+
61+
```php title="mod/example/classes/hook_listener.php"
62+
<?php
63+
64+
namespace mod_example;
65+
66+
use core\hook\di_configuration;
67+
68+
class hook_listener {
69+
public static function inject_dependencies(di_configuration $hook): void {
70+
$hook->add_definition(
71+
id: complex_client::class,
72+
definition: function (
73+
\moodle_database $db,
74+
): complex_client {
75+
global $CFG;
76+
77+
return new complex_client(
78+
db: $db,
79+
name: $CFG->some_value,
80+
);
81+
}
82+
)
83+
}
84+
}
85+
```
86+
87+
</TabItem>
88+
89+
</Tabs>
90+
91+
## Mocking dependencies in Unit Tests
92+
93+
One of the most convenient features of Dependency Injection is the ability to provide a mocked version of the dependency during unit testing.
94+
95+
Moodle resets the Dependency Injection Container between each unit test, which means that little-to-no cleanup is required.
96+
97+
```php title="Injecting a Mocked dependency"
98+
<?php
99+
namespace mod_example;
100+
101+
use GuzzleHttp\Handler\MockHandler;
102+
use GuzzleHttp\HandlerStack;
103+
use GuzzleHttp\Middleware;
104+
use GuzzleHttp\Psr7\Response;
105+
106+
class example_test extends \advanced_testcase {
107+
public function test_the_thing(): void {
108+
// Mock our responses to the http_client.
109+
$handlerstack = HandlerStack::create(new MockHandler([
110+
new Response(200, [], json_encode(['name' => 'Colin'])),
111+
]));
112+
113+
// Inject the mock.
114+
\core\di::set(
115+
\core\http_client::class,
116+
new http_client(['handler' => $handlerstack]),
117+
);
118+
119+
// Call a method on the example class.
120+
// This method uses \core\di to fetch the client and use it to fetch data.
121+
$example \core\di::get(example::class);
122+
$result = $example->do_the_thing();
123+
124+
// The result will be based on the mock response.
125+
$this->assertEquals('Colin', $result->get_name());
126+
}
127+
}
128+
```
129+
130+
## Injecting the container into classes
131+
132+
In more advanced cases you may wish to make use of dependency injection within an object. One way that you can do so is to inject the dependency into the class via its constructor, for example:
133+
134+
```php title="Injecting the ContainerInterface"
135+
<?php
136+
137+
namespace mod_example;
138+
139+
use Psr\Container\ContainerInterface;
140+
141+
class example {
142+
/**
143+
* @param ContainerInterface $container
144+
*/
145+
public function __construct(
146+
protected ContainerInterface $container,
147+
) {
148+
}
149+
150+
public function do_something(string $value): string {
151+
return $this->get(\core\formatting::class)->format_string($value);
152+
}
153+
}
154+
```
155+
156+
The `example` class can also be fetched using DI:
157+
158+
```php title="Consuming the example class"
159+
use mod_example\example;
160+
161+
// ...
162+
$example = \core\di::get(example::class);
163+
$value = $example->do_something("with this string");
164+
```
165+
166+
## Advanced usage
167+
168+
All usage of the Container _should_ be via `\core\di`, which is a wrapper around the currently-active Container implementation. In normal circumstances it is not necessary to access the underlying Container implementation directly and such usage is generally discouraged.
169+
170+
:::danger
171+
172+
Moodle currently makes use of PHP-DI as its Container implementation.
173+
174+
Please note that the underlying Dependency Injection system _may_ change at any time.
175+
176+
Care should be taken to only make use of methods which are defined in the [PSR-11 Container Interface](https://www.php-fig.org/psr/psr-11/).
177+
178+
:::
179+
180+
### Resetting the Container
181+
182+
The Container is normally instantiated during the bootstrap phase of a script. In normal use it is not reset and there should be no need to reset it, however it is _possible_ to reset it if required. This usage is intended to be used for situations such as Unit Testing.
183+
184+
:::danger
185+
186+
Resetting an actively-used container can lead to unintended consequences.
187+
188+
:::
189+
190+
```php title="Resetting the Container"
191+
\core\di::reset_container():
192+
```
193+
194+
### Accessing the Container Interface
195+
196+
In some rare circumstances you may need to perform certain advanced tasks such as accessing the `ContainerInterface` implementation directly.
197+
198+
The `\core\di` wrapper provides a method to fetch the `\Psr\Container\ContainerInterface` implementation.
199+
200+
```php title="Fetch the ContainerInterface"
201+
$container = \core\di::get_container();
202+
```

docs/apis/subsystems/output/index.md

+3-15
Original file line numberDiff line numberDiff line change
@@ -221,15 +221,11 @@ The key parameter for this function is:
221221

222222
#### format_text()
223223

224-
```php
225-
function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseid_do_not_use = null)
226-
```
227-
228224
This function should be used to:
229225

230226
- print **any html/plain/markdown/moodle text**, needing any of the features below. It is mainly used for long strings like posts, answers, glossary items, etc.
231227
- filter content through Moodle or 3rd party language filters for multi-language support. Not to be confused with [get_string](https://docs.moodle.org/dev/String_API#get_string.28.29) which is used to access localized strings in Moodle and its language packs. Together, these functions enable Moodle multi-language support .
232-
Note that this function is really **heavy** because it supports **cleaning** of dangerous contents, delegates processing to enabled **content filter**s, supports different **formats** of text (HTML, PLAIN, MARKDOWN, MOODLE) and performs a lot of **automatic conversions** like adding smilies, build links. Also, it includes a strong **cache mechanism** (DB based) that will alleviate the server from a lot of work processing the same texts time and again.
228+
Note that this function is really **heavy** because it supports **cleaning** of dangerous contents, delegates processing to enabled **content filters**, supports different **formats** of text (HTML, PLAIN, MARKDOWN, MOODLE) and performs a lot of **automatic conversions** like adding smilies, build links. Also, it includes a strong **cache mechanism** (DB based) that will alleviate the server from a lot of work processing the same texts time and again.
233229

234230
Some interesting parameters for this function are:
235231

@@ -241,18 +237,12 @@ Some interesting parameters for this function are:
241237
- `options->context`: If text is filtered (and this happens by default), it is very important to specify context (id or object) for applying filters. If context is not specified it will be taken from `$PAGE->context` and may potentially result in displaying the same text differently on different pages. For example all module-related information should have module context even when it appears in course-level reports, all course-related information such as name and description should have course context even when they are displayed on front page or system pages.
242238
- `options->param`: To decide if you want every paragraph automatically enclosed between html paragraph tags (`<p>...</p>`) (defaults to true). This option only applies to `FORMAT_MOODLE`.
243239
- `options->newlines`: To decide if line feeds in text should be converted to html newlines (`<br />`) (defaults to true). This option only applies to `FORMAT_MOODLE`.
244-
- `options->nocache`: If true the string will not be cached and will be formatted every call. Default false.
245240
- `options->overflowdiv`*: If set to true the formatted text will be encased in a div with the class no-overflow before being returned. Default false.
246241
- `options->allowid` : If true then id attributes will not be removed, even when using HTML Purifier. Default false.
247242
- `options->blanktarget` : If true all `<a>` tags will have `target="_blank"` added unless target is explicitly specified. Default false.
248-
- **courseid_do_not_use**: This parameter was earlier used to help applying filters but now is replaced with more precise `$options->context`, see above
249243

250244
#### format_string()
251245

252-
```php
253-
function format_string ($string, $striplinks = true, $options = null)
254-
```
255-
256246
This function should be used to:
257247

258248
- print **short non-html strings that need filter processing** (activity titles, post subjects, glossary concepts...). If the string contains HTML, it will be filtered out. If you want the HTML, use `format_text()` instead.
@@ -269,14 +259,12 @@ Some interesting parameters for this function are:
269259
- `options->escape`: To decide if you want to escape HTML entities. True by default.
270260
- `options->filter`: To decide if you want to allow filters to process the text (defaults to true). This is ignored by `FORMAT_PLAIN` for which filters are never applied.
271261

272-
:::note
273-
In earlier versions of Moodle, the third argument was integer `$courseid`. It is still supported for legacy - if the third argument is an integer instead of an array or object, it is considered to be course id and is this course's context is passed to the filters being applied.
274-
:::
275-
276262
### Simple elements rendering
277263

278264
:::important
265+
279266
Those methods are designed to replace the old ```html_writer::tag(...)``` methods. Even if many of them are just wrappers around the old methods, they are more semantic and could be overridden by component renderers.
267+
280268
:::
281269

282270
While to render complex elements, you should use [templates](../../../guides/templates/index.md), some simple elements can be rendered using the following functions:

0 commit comments

Comments
 (0)