Tutorial: Integrating SVG Icons with swarm-icons
Introduction
Section titled “Introduction”In this tutorial, you will integrate the swarm-icons ↗ PHP library into your Slim MVC project. This library provides a framework-agnostic way to render inline SVG icons in your PHP views, with access to 27 pre-installed icon sets including Tabler, Heroicons, Lucide, Material Design Icons, and more.
By the end of this tutorial, you will be able to render icons like this in any view:
<h1><?= swarm_icon('tabler:home') ?> Dashboard</h1>Learning Objectives
Section titled “Learning Objectives”By completing this tutorial, you will be able to:
- Install a PHP library via Composer in an existing Slim 4 project.
- Register a new service in the application’s DI (Dependency Injection) container.
- Configure the swarm-icons icon manager during the application bootstrap.
- Render SVG icons in plain PHP views using the
swarm_icon()helper function. - Customize icon attributes (size, CSS classes, fill, stroke) using the fluent API.
- Search for available icons using the swarm-icons CLI tool.
Prerequisites
Section titled “Prerequisites”- A working Slim MVC project (e.g.,
brew-finder-appfrom the MVC lab). - Wampoon and VS Code.
- Composer (bundled with Wampoon).
- Basic familiarity with the Slim MVC project structure (controllers, views, routes).
Browsing Icons
Section titled “Browsing Icons”Use these websites to browse and search for icons by name before using them in your project:
- Tabler Icons ↗: 6,000+ stroke-based icons.
- Lucide Icons ↗: 1,700+ stroke-based icons.
- Iconify ↗: Browse and search across 200+ icon sets in one place.
Lab Steps
Section titled “Lab Steps”Step 1: Install swarm-icons via Composer
Section titled “Step 1: Install swarm-icons via Composer”Objective: Add the swarm-icons library to your project dependencies.
Instructions:
- Open a terminal in VS Code and run the following Composer command to install the library:
"../../composer.bat" require frostybee/swarm-icons- Verify the installation succeeded by checking that
vendor/frostybee/swarm-icons/exists in your project.
Step 2: Add a Composer Script Shortcut
Section titled “Step 2: Add a Composer Script Shortcut”Objective: Add a Composer script alias so you don’t have to type the full path to the swarm-icons CLI every time.
Instructions:
- Open your
composer.jsonfile - Add a
"swarm"entry to the"scripts"section:
"scripts": { "start": "php -S localhost:8080 -t public public/index.php", "swarm": "@php vendor/bin/swarm-icons", "post-create-project-cmd": [ "@php -r \"file_exists('config/env.php') || copy('config/env.example.php', 'config/env.php');\"" ]}- Save the file
Now instead of typing "../../php.bat" vendor/bin/swarm-icons every time, you can use the shorter:
"../../composer.bat" swarm -- <command>Step 3: Download Icon Sets
Section titled “Step 3: Download Icon Sets”Objective: Use the swarm-icons CLI to download the icon sets you want to use in your project.
Instructions:
- Run the following command to download a few popular icon sets into
public/assets/svg-icons/:
"../../composer.bat" swarm -- json:download tabler heroicons lucide --dest=public/assets/svg-iconsThis downloads the Tabler, Heroicons, and Lucide icon sets as JSON files into your project’s public/assets/svg-icons/ directory.
- To see all available popular sets and their download status, run:
"../../composer.bat" swarm -- json:download --list- Alternatively, download all popular sets at once:
"../../composer.bat" swarm -- json:download --all --dest=public/assets/svg-iconsStep 4: Register the IconManager in the DI Container
Section titled “Step 4: Register the IconManager in the DI Container”Objective: Add the icon manager as a service definition in the application’s dependency injection container and wire up the global swarm_icon() helper.
Instructions:
- Open your
config/container.phpfile - Add the following
usestatements at the top of the file, alongside the existing imports:
use Frostybee\SwarmIcons\SwarmIcons;use Frostybee\SwarmIcons\IconManager;use Frostybee\SwarmIcons\SwarmIconsConfig;- Add the
IconManagerdefinition to the$definitionsarray, after the existingPDOServicedefinition:
IconManager::class => function () { $manager = SwarmIconsConfig::create() ->discoverJsonSets(APP_BASE_DIR_PATH . '/public/assets/svg-icons') ->cachePath(APP_BASE_DIR_PATH . '/var/cache/icons') ->defaultPrefix('tabler') ->defaultAttributes([ 'width' => '24', 'height' => '24', 'fill' => 'none', 'stroke' => 'currentColor', 'stroke-width' => '2', ]) ->build();
// Wire the icon manager to the global swarm_icon() helper. SwarmIcons::setManager($manager);
return $manager;},- Open your
config/bootstrap.phpfile and add the following line after the container is built (after->build()) and before theAppis retrieved:
// Boot the IconManager so the global swarm_icon() helper is available in views.$container->get(\Frostybee\SwarmIcons\IconManager::class);This eagerly resolves the IconManager from the container, which triggers the factory you defined above and calls SwarmIcons::setManager(). Without this line, the container definition is lazy: it only runs when something explicitly requests IconManager::class. The swarm_icon() helper would throw a “No IconManager instance set” error in your views.
- Save both files
What each configuration method does:
discoverJsonSets(path): Scans the given directory for JSON icon set files and registers them. We point it topublic/assets/svg-icons/where you downloaded your icon sets in Step 3.cachePath(): Sets the directory for caching parsed icons. We usevar/cache/iconsfollowing the project’s convention of storing runtime data invar/.defaultPrefix('tabler'): Lets you writeswarm_icon('home')instead ofswarm_icon('tabler:home')for convenience.defaultAttributes(): Sets sensible default SVG attributes for all icons. The values shown above are optimized for stroke-based icon sets like Tabler and Heroicons.SwarmIcons::setManager($manager): Registers the manager globally so theswarm_icon()helper function works in all view templates.
Step 5: Render Icons in a View
Section titled “Step 5: Render Icons in a View”Objective: Use the swarm_icon() helper to display SVG icons in your PHP view templates.
Instructions:
- Open an existing view file (e.g.,
app/Views/homeView.php) - Add icons using the
swarm_icon()helper with<?= ?>short echo tags:
<?phpuse App\Helpers\ViewHelper;$page_title = 'Home';ViewHelper::loadHeader($page_title);?>
<div class="container mt-4"> <h1><?= swarm_icon('tabler:home') ?> Welcome</h1>
<nav class="mb-4"> <a href="#"><?= swarm_icon('tabler:users') ?> Users</a> <a href="#" class="ms-3"><?= swarm_icon('tabler:settings') ?> Settings</a> <a href="#" class="ms-3"><?= swarm_icon('heroicons:magnifying-glass') ?> Search</a> </nav>
<p> Status: <?= swarm_icon('tabler:circle-check', ['class' => 'text-success']) ?> Active </p></div>
<?phpViewHelper::loadJsScripts();ViewHelper::loadFooter();?>- Save the file and visit the page in your browser
Key points:
swarm_icon()returns anIconobject that implementsStringable, so<?= ?>automatically outputs the<svg>markup.- The
prefix:nameformat (e.g.,tabler:home) identifies which icon set and which icon to render. - Since we set
defaultPrefix('tabler')in Step 4, you can also writeswarm_icon('home')as a shorthand for Tabler icons. - To use icons from other sets, specify the prefix explicitly:
swarm_icon('heroicons:magnifying-glass'),swarm_icon('lucide:star').
Step 6: Style Icons with CSS
Section titled “Step 6: Style Icons with CSS”Objective: Add basic CSS rules to control how icons appear within your page layout.
Instructions:
- Open (or create) your stylesheet at
public/assets/css/style.cssand add the following rules:
/* Align inline SVG icons with surrounding text */svg { display: inline-block; vertical-align: middle;}
/* Color utility classes for icons */.text-success { color: #28a745; }.text-danger { color: #dc3545; }.text-primary { color: #007bff; }.text-warning { color: #ffc107; }.text-muted { color: #6c757d; }- Make sure the stylesheet is linked in
app/Views/common/header.php:
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><?= $page_title ?></title> <link href="<?= asset_url('/css/style.css') ?>" rel="stylesheet"></head>- Save both files and refresh the page
How icon colors work:
Because the defaultAttributes set stroke="currentColor", stroke-based icons (Tabler, Heroicons, Lucide) inherit the text color from their parent element. This means:
<!-- The icon inherits the red color from the CSS class --><span class="text-danger"><?= swarm_icon('tabler:alert-triangle') ?> Error</span>Step 7: Customize Icons with the Fluent API
Section titled “Step 7: Customize Icons with the Fluent API”Objective: Learn to modify icon attributes using method chaining for more advanced customization.
Instructions:
The swarm_icon() function returns an Icon object with a fluent API. You can chain methods to customize the icon before it is rendered:
<!-- Change icon size -->Small: <?= swarm_icon('tabler:star')->size(16) ?>Medium: <?= swarm_icon('tabler:star')->size(24) ?>Large: <?= swarm_icon('tabler:star')->size(48) ?>
<!-- Add CSS classes --><?= swarm_icon('tabler:heart')->class('text-danger')->size(32) ?>
<!-- Change fill color (for solid/fill-based icon sets) --><?= swarm_icon('fa6-solid:star')->fill('#ffc107')->size(32) ?>
<!-- Adjust stroke width (for outline/stroke-based icon sets) --><?= swarm_icon('tabler:alert-triangle')->strokeWidth(1.5)->size(32) ?>
<!-- Full method chain --><?= swarm_icon('tabler:rocket') ->size(48) ->class('text-primary') ->strokeWidth(1.5)?>Alternative: Pass attributes as an array:
Instead of chaining methods, you can pass an associative array as the second argument:
<?= swarm_icon('mdi:github', [ 'width' => '32', 'height' => '32', 'class' => 'text-dark', 'fill' => 'currentColor',]) ?>Stroke-based vs Fill-based icon sets:
| Rendering Style | Icon Sets | Key Attribute |
|---|---|---|
| Stroke-based (outline icons) | Tabler, Heroicons, Lucide, Phosphor | stroke="currentColor" |
| Fill-based (solid icons) | MDI, Font Awesome, Bootstrap Icons | fill="currentColor" |
When using a fill-based icon set, override the default attributes:
<?= swarm_icon('mdi:home', ['fill' => 'currentColor', 'stroke' => 'none']) ?>Step 8: Search for Icons Using the CLI
Section titled “Step 8: Search for Icons Using the CLI”Objective: Use the swarm-icons command-line tool to discover available icons by name.
Instructions:
- Open a terminal in VS Code and run a search command:
"../../composer.bat" swarm -- icon:search tabler arrowThis searches the tabler icon set for all icons containing “arrow” in their name.
- Try more search examples:
# List all icons in the heroicons set"../../composer.bat" swarm -- icon:list heroicons
# Search lucide icons for "user""../../composer.bat" swarm -- icon:search lucide user
# Search for "home" icons in the mdi set"../../composer.bat" swarm -- icon:search mdi homeThe output shows the full prefix:name format that you can copy directly into your swarm_icon() calls in your view code.
Quick Reference
Section titled “Quick Reference”Fluent API Methods
Section titled “Fluent API Methods”| Method | Description | Example |
|---|---|---|
size($px) | Set width and height | ->size(32) |
class($css) | Add CSS classes | ->class('text-primary') |
fill($color) | Set fill color | ->fill('currentColor') |
stroke($color) | Set stroke color | ->stroke('#333') |
strokeWidth($w) | Set stroke width | ->strokeWidth(1.5) |
Common Tabler Icons
Section titled “Common Tabler Icons”Browse the full Tabler icon set on Iconify ↗.
| Icon | Code |
|---|---|
| Home | swarm_icon('tabler:home') |
| User | swarm_icon('tabler:user') |
| Search | swarm_icon('tabler:search') |
| Settings | swarm_icon('tabler:settings') |
| Edit | swarm_icon('tabler:edit') |
| Trash | swarm_icon('tabler:trash') |
| Plus | swarm_icon('tabler:plus') |
| Check | swarm_icon('tabler:check') |
| X (Close) | swarm_icon('tabler:x') |
| Arrow Left | swarm_icon('tabler:arrow-left') |
| Star | swarm_icon('tabler:star') |
| Heart | swarm_icon('tabler:heart') |
| Eye | swarm_icon('tabler:eye') |
| Download | swarm_icon('tabler:download') |
| Alert Triangle | swarm_icon('tabler:alert-triangle') |
Troubleshooting
Section titled “Troubleshooting”| Issue | Cause | Fix |
|---|---|---|
| ”No IconManager instance set” error | config/bootstrap.php is missing the SwarmIcons::setManager() call | Verify that you added the line after the container is built (Step 4) |
| Icons render as empty space | Stroke/fill attributes do not match the icon set style | Use stroke="currentColor" for outline sets (Tabler, Heroicons) or fill="currentColor" for solid sets (MDI, FA) |
| Icons appear too large or too small | Default size does not match your layout | Use ->size(16) or ->size(32) to adjust, or update defaultAttributes in container.php |
| Cache permission error | The var/cache/ directory is not writable | Ensure the web server has write permission to the var/ directory |