Manual:LinkBatch.php

From Linux Web Expert

Revision as of 01:10, 25 February 2024 by imported>Shirayuki
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Description

When MediaWiki renders a page, it must go through all of the links in the page to see whether or not they actually exist. If they don't exist, a "new" class is added to the anchor tag so that it will be shown as a redlink. If the page has a lot of links, this can become an expensive process that slows down rendering the page. To eliminate this problem, the LinkCache class was created. A LinkCache object stores cached information about all the pages linked from one source (typically a page). Generating the LinkCache itself is still expensive, however, if each linked page is queried separately. To get around this problem, the LinkBatch class can be used. The LinkBatch class allows all the pages to be added to a batch query so that only one call to the database is necessary.

Usage

To use LinkBatch for your page, first instantiate a new LinkBatch object:

$batch = $this->linkBatchFactory->newLinkBatch();

This assumes that you use Dependency Injection , and that the LinkBatchFactory was injected into the class.

Then, you should register yourself as the caller of the LinkBatch so that the database query can be traced back to you:

$batch->setCaller( __METHOD__ );

Then add each linked page to the batch. There are two ways to do this: with the linked page's LinkTarget object, or with the linked page's namespace and title string.

Using LinkTarget object:

$batch->addObj( $linkTarget );

Using namespace and title string:

$batch->add( $namespace, $title );

Once all the linked pages are added to the batch, use the execute function to generate and store the LinkCache:

$batch->execute();

If you know beforehand that the links you are creating definitely exist, you can prevent them from being checked for existence by using the LinkRenderer::makeKnownLink() function. This eliminates the need for the LinkCache.