How to Use createSitemap()->updateRobots() Method Chaining in PHP Sitemap Generator

The SunSitemap class implements a fluent interface where createSitemap() and updateRobots() both return $this, enabling you to chain these calls together with addUrl() to generate sitemaps and update robots.txt in a single expression.

The msbatal/php-sitemap-generator repository provides a lightweight solution for XML sitemap generation. By leveraging method chaining with createSitemap()->updateRobots(), you can streamline your workflow to add URLs, write sitemap files, and synchronize your robots.txt file without managing intermediate variables between steps.

How the Fluent Interface Works

In SunSitemap.php, the class is designed to support method chaining through consistent return $this; statements. When you invoke createSitemap(), the method processes the internal URL collection, writes the XML files to your specified relative path, and returns the current instance. Similarly, updateRobots() modifies or creates the robots.txt file to include the Sitemap: directive pointing to your generated file, then returns $this.

This pattern allows the object instance to flow through multiple operations. According to the source code in SunSitemap.php, both methods conclude with return $this; (visible at the end of the method implementations around lines 75 and 86), passing the same SunSitemap object along the chain to subsequent calls.

Implementing the Method Chain

Initialize the Generator

Start by instantiating the SunSitemap class with your base URL and relative path. The constructor, located at line 111 in SunSitemap.php, accepts the base URL and the directory path where sitemap files will be stored.

require_once 'SunSitemap.php';

$generator = new SunSitemap('https://example.com', 'public/');

Add URLs to the Collection

Use the addUrl() method (defined at line 48 in SunSitemap.php) to populate the internal $urls array. You can pass a simple string or an array containing the URL, last modification date, change frequency, and priority.

$generator->addUrl('index.html')
          ->addUrl('about.html', '2024-01-01', 'monthly', '0.8')
          ->addUrl(['contact.html', '2024-01-10', 'weekly', '0.7']);

Generate the Sitemap

The createSitemap() method processes the accumulated URLs, handles chunking for large collections (respecting the maxUrl limit), writes sitemap.xml or sitemap-index.xml to disk, and optionally creates gzip compressed versions. As implemented in SunSitemap.php at line 86, this method concludes with return $this; to maintain the chain.

$generator->createSitemap();

Update robots.txt

Finally, updateRobots() reads the existing robots.txt file (or creates one), injects the Sitemap: line pointing to your generated sitemap URL, and writes the file back to the filesystem. Located at line 75 in SunSitemap.php, this method also returns $this, completing the chain.

$generator->updateRobots();

Complete Code Examples

Basic Usage

This example demonstrates the complete createSitemap()->updateRobots() method chain from instantiation to file generation:

<?php
require_once 'SunSitemap.php';

$generator = (new SunSitemap('https://example.com', 'public/'))
                ->addUrl('index.html')
                ->addUrl('about.html', '2024-01-01', 'monthly', '0.8')
                ->addUrl(['contact.html', '2024-01-10', 'weekly', '0.7'])
                ->createSitemap()
                ->updateRobots();

echo "Sitemap created at: {$generator->sitemapUrl}\n";
echo "Memory used: {$generator->memoryUsage()} MB\n";
echo "Duration: {$generator->showDuration()} s\n";
?>

Advanced Configuration with Options

You can customize the generator by passing additional parameters to the constructor: the maximum URLs per file and a boolean to enable gzip compression. This example chains these options with the standard workflow:

<?php
require_once 'SunSitemap.php';

$gen = (new SunSitemap('https://myshop.com', 'sitemaps/', 10000, true))
            ->addUrl(['product/1.html', '2024-02-01', 'daily', '1.0'])
            ->addUrl(['product/2.html'])
            ->createSitemap()
            ->updateRobots();

echo "Robots.txt written to {$gen->absPath}{$gen->robotsFile}\n";
?>

Summary

  • Fluent Interface: The SunSitemap class implements method chaining by returning $this from addUrl(), createSitemap(), and updateRobots().
  • Source Location: The chaining logic is implemented in SunSitemap.php (lines 48, 75, 86, and 111), with both file-writing methods concluding with return $this;.
  • Execution Order: You must call addUrl() before createSitemap(), and createSitemap() before updateRobots(), as the latter depends on the sitemap file existing to reference its URL.
  • File Outputs: The chain generates sitemap.xml (or indexed variants) and automatically updates robots.txt with the appropriate Sitemap: directive.

Frequently Asked Questions

What methods in SunSitemap support chaining?

The addUrl(), createSitemap(), and updateRobots() methods all support chaining. Each method returns the current SunSitemap instance ($this), allowing you to link multiple operations into a single statement without intermediate assignment.

Does createSitemap() return the file path or the object?

The createSitemap() method returns the SunSitemap object itself ($this), not the file path. To access the generated sitemap URL, reference the $sitemapUrl property on the instance after the chain completes, as shown in the test examples.

Can I add more URLs after calling createSitemap()?

While the object remains mutable and technically accepts additional addUrl() calls, createSitemap() processes the current state of the internal $urls array at the moment of invocation. Any URLs added after calling createSitemap() would require another call to createSitemap() to be included in the XML files.

Where does updateRobots() create the robots.txt file?

The updateRobots() method writes the robots.txt file to the relative path specified in the constructor ($relPath), combined with the absolute path resolution stored in $absPath. You can verify the location by checking the {$gen->absPath}{$gen->robotsFile} properties after execution.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →