tobento / service-minify
A lightweight and extensible PHP service for minifying CSS, JavaScript, and HTML.
Installs: 1
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/tobento/service-minify
Requires
- php: >=8.4
Requires (Dev)
- phpunit/phpunit: ^12.3
- vimeo/psalm: ^6.13
README
The Minify Service provides a flexible and extensible way to minify CSS, HTML, and JavaScript content.
It is built around small, composable Modifiers that can be combined to create highly optimized minifiers tailored to your needs.
The service is designed to be framework-agnostic and works seamlessly in any PHP application.
Requirements
- PHP 8.4 or greater
Highlights
- Framework-agnostic, works with any project
- Decoupled design for maximum flexibility
Table of Contents
- Getting started
- Documentation
- Credits
Getting started
Add the latest version of the minify project running this command.
composer require tobento/service-minify
Requirements
- PHP 8.4 or above
Documentation
Basic Usage
The recommended way to create a minifier is by using one of the built-in factories.
Factories provide sensible defaults and allow you to easily enable or disable specific modifiers.
use Tobento\Service\Minify\Factory\CssMinifierFactory; // Create a CSS minifier with all default modifiers $minifier = new CssMinifierFactory()->createMinifier(); $minified = $minifier->minify($css);
You may customize the minifier by adding or removing modifiers:
use Tobento\Service\Minify\Factory\CssMinifierFactory; $factory = new CssMinifierFactory() // exclude built-in modifiers by key ->except('comments') // or use only the specified built‑in modifiers ->only('leading-zero') // append a custom modifier instance ->addModifier(new MyCustomModifier()) // or prepend one to run it before all others ->prependModifier(new MyCustomModifier()); $minifier = $factory->createMinifier();
If you prefer full manual control, you may still create a minifier directly by passing a Modifiers collection:
use Tobento\Service\Minify\Minifier; use Tobento\Service\Minify\Modifier; $minifier = new Minifier\Css( new Modifier\Modifiers( new Modifier\Css\Comments(), new Modifier\Css\Colors(), new Modifier\Css\Whitespaces(), ) ); $minified = $minifier->minify($css);
Each minifier accepts a modifiers collection, giving you full control over the minification pipeline.
If you need a minifier that performs no changes, you may use the Null Minifier.
Available Minifiers
CSS Minifier
The CSS minifier applies a sequence of CSS-specific modifiers to optimize and compress stylesheet content.
use Tobento\Service\Minify\CssMinifierInterface; use Tobento\Service\Minify\Minifier; use Tobento\Service\Minify\MinifierInterface; use Tobento\Service\Minify\Modifier; $minifier = new Minifier\Css( new Modifier\Modifiers( new Modifier\Css\Charsets(), // handles @charset; typically placed early new Modifier\Css\Comments(), // remove comments early new Modifier\Css\Colors(), // normalize color values new Modifier\Css\FontWeights(), // normalize named weights new Modifier\Css\Quotes(), // remove unnecessary quotes new Modifier\Css\Semicolons(), // remove trailing semicolons new Modifier\Css\LeadingZero(), // 0.5 → .5 new Modifier\Css\ZeroUnits(), // 0px → 0 new Modifier\Css\ZeroValues(), // .0 → 0 new Modifier\Css\Whitespaces(), // final cleanup ) ); var_dump($minifier instanceof CssMinifierInterface); // bool(true) var_dump($minifier instanceof MinifierInterface); // bool(true) // Minifying CSS $minified = $minifier->minify($css);
A full list of available modifiers can be found under the CSS Modifiers section.
HTML Minifier
The HTML minifier applies a sequence of HTML-specific modifiers to reduce markup size while preserving the original structure and meaning.
use Tobento\Service\Minify\HtmlMinifierInterface; use Tobento\Service\Minify\Minifier; use Tobento\Service\Minify\MinifierInterface; use Tobento\Service\Minify\Modifier; $minifier = new Minifier\Html( new Modifier\Modifiers( new Modifier\Html\Attributes(), // normalize and trim attributes new Modifier\Html\Comments(), // remove HTML comments new Modifier\Html\Doctype(), // normalize doctype new Modifier\Html\OptionalTags(), // remove optional closing tags new Modifier\Html\Whitespaces(), // collapse and trim whitespace ) ); var_dump($minifier instanceof HtmlMinifierInterface); // bool(true) var_dump($minifier instanceof MinifierInterface); // bool(true) // Minifying HTML $minified = $minifier->minify($html);
A full list of available modifiers can be found under the HTML Modifiers section.
JavaScript Minifier
The JavaScript minifier applies JavaScript-specific modifiers to reduce script size while preserving behavior and execution semantics.
use Tobento\Service\Minify\JavaScriptMinifierInterface; use Tobento\Service\Minify\Minifier; use Tobento\Service\Minify\MinifierInterface; use Tobento\Service\Minify\Modifier; $minifier = new Minifier\JavaScript( new Modifier\Modifiers( new Modifier\JavaScript\Comments(), // remove comments new Modifier\JavaScript\Semicolons(), // remove unnecessary semicolons new Modifier\JavaScript\Whitespaces(), // collapse and trim whitespace ) ); var_dump($minifier instanceof JavaScriptMinifierInterface); // bool(true) var_dump($minifier instanceof MinifierInterface); // bool(true) // Minifying JavaScript $minified = $minifier->minify($js);
A full list of available modifiers can be found under the JavaScript Modifiers section.
Null Minifier
The Null Minifier performs no transformations and returns the content exactly as provided.
It is useful when minification should be disabled without changing application logic.
use Tobento\Service\Minify\Minifier; use Tobento\Service\Minify\MinifierInterface; $minifier = new Minifier\NullMinifier(); var_dump($minifier instanceof MinifierInterface); // bool(true) // No changes are applied $minified = $minifier->minify($content); var_dump($minified === $content); // bool(true)
This minifier is ideal for development environments or scenarios where minification must be conditionally bypassed.
Available Modifiers
CSS Modifiers
Charsets CSS Modifier
The Charsets modifier normalizes and optimizes @charset declarations. It ensures that only a single, valid charset appears at the top of the stylesheet and removes any redundant or misplaced declarations.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\Css\Charsets(); $css = '@charset "UTF-8"; body { color: red; }'; $modified = $modifier->modify($css); // '@charset "utf-8"; body { color: red; }'
This modifier is typically run early to ensure the @charset declaration is handled before other transformations, although it can safely run in any position since it normalizes and relocates the charset automatically.
Colors CSS Modifier
The Colors modifier normalizes color values by converting named colors and long-form hex codes into their shortest valid representations. This helps reduce stylesheet size while preserving exact visual output.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\Css\Colors(); $css = 'body { color: #ff0000; background: red; }'; $modified = $modifier->modify($css); // 'body { color: #f00; background: red; }'
This modifier focuses purely on color normalization and can be placed anywhere in the modifier sequence.
Comments CSS Modifier
The Comments modifier removes CSS comments (/* ... */) that are safe to eliminate, helping reduce stylesheet size without affecting rendering or behavior.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\Css\Comments(); $css = '/* header */ body { color: red; } /* footer */'; $modified = $modifier->modify($css); // 'body { color: red; }'
This modifier focuses solely on stripping comments and can be placed early in the modifier sequence to simplify later processing.
Font Weights CSS Modifier
The FontWeights modifier normalizes named font-weight keywords (such as bold or normal) into their numeric equivalents. This reduces size and ensures consistent representation across the stylesheet.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\Css\FontWeights(); $css = 'h1 { font-weight: bold; } p { font-weight: normal; }'; $modified = $modifier->modify($css); // 'h1 { font-weight: 700; } p { font-weight: 400; }'
This modifier focuses solely on converting named weights to numeric values and can be placed anywhere in the modifier sequence.
Leading Zero CSS Modifier
The LeadingZero modifier removes unnecessary leading zeros from decimal values, reducing size without affecting meaning. For example, 0.5 becomes .5
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\Css\LeadingZero(); $css = '.foo { opacity: 0.5; margin-left: 0.25em; }'; $modified = $modifier->modify($css); // '.foo { opacity: .5; margin-left: .25em; }'
This modifier focuses solely on trimming leading zeros and can be placed anywhere in the modifier sequence.
Quotes CSS Modifier
The Quotes modifier removes unnecessary quotation marks in CSS attribute selectors, reducing size while preserving correct selector behavior.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\Css\Quotes(); $css = 'input[type="text"] { color: red; }'; $modified = $modifier->modify($css); // 'input[type=text] { color: red; }'
This modifier affects only attribute selectors (e.g., [type="text"] to [type=text]) and leaves all other quoted values such as strings or font-family names untouched.
Semicolons CSS Modifier
The Semicolons modifier normalizes redundant semicolons in CSS declarations by replacing multiple consecutive semicolons with a single one. This helps clean up malformed or overly verbose CSS without altering valid syntax.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\Css\Semicolons(); $css = ".foo { color: red;; margin: 0;; }"; $modified = $modifier->modify($css); // '.foo { color: red; margin: 0; }'
This modifier affects only consecutive semicolons (e.g., ;; into ;) and leaves valid single semicolons untouched. It does not add missing semicolons or modify spacing beyond the redundant sequences it removes.
Whitespaces CSS Modifier
The Whitespaces modifier removes unnecessary whitespace from CSS, reducing file size while preserving valid syntax. It collapses redundant spaces, tabs, and line breaks, and tightens common CSS patterns without altering semantics.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\Css\Whitespaces(); $css = " .foo { color: red; margin: 0; } "; $modified = $modifier->modify($css); // '.foo{color:red;margin:0;}'
This modifier focuses on structural whitespace cleanup - such as removing extra spaces around braces, colons, semicolons, and between rules - while leaving meaningful whitespace (e.g., inside strings) untouched.
Zero Units CSS Modifier
The ZeroUnits modifier removes unnecessary units from zero‑values in CSS declarations.
Values like 0px, 0em, or 0% are normalized to plain 0, reducing size while keeping the CSS valid.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\Css\ZeroUnits(); $css = ".foo { margin: 0px; padding: 0em 10px; }"; $modified = $modifier->modify($css); // '.foo { margin: 0; padding: 0 10px; }'
This modifier affects only values where the numeric part is exactly zero.
Non-zero values (e.g., 0.5px, 10px) remain unchanged.
Zero Values CSS Modifier
The ZeroValues modifier normalizes zero-like numeric values to a plain 0.
It converts variants such as 0.0, .0, 0., or 00 into a consistent 0, helping clean up malformed or inconsistent CSS values.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\Css\ZeroValues(); $css = ".foo { margin: 0.0; padding: 00; line-height: .0; }"; $modified = $modifier->modify($css); // '.foo { margin: 0; padding: 0; line-height: 0; }'
This modifier affects only values that are effectively zero.
Non-zero values such as 0.5 or 0.75 remain unchanged - those are handled by the Leading Zero modifier instead.
HTML Modifiers
Attributes HTML Modifier
The Attributes modifier removes redundant or unnecessary HTML attributes and normalizes certain boolean attributes.
It cleans up markup by stripping empty attributes, removing obsolete type declarations, and simplifying boolean attributes without altering the meaning of the HTML.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\Html\Attributes(); $html = '<script type="text/javascript"></script><div class="" disabled="disabled"></div>'; $modified = $modifier->modify($html); // '<script></script><div disabled></div>'
This modifier performs the following cleanups:
- Removes empty attributes such as
class="",id="", orstyle="". - Removes obsolete script and style types (
type="text/javascript"andtype="text/css"). - Normalizes boolean attributes by converting patterns like
disabled="disabled"todisabled.
It does not modify attribute values, reorder attributes, or alter any other HTML semantics.
Comments HTML Modifier
The Comments modifier removes standard HTML comments while preserving conditional comments used by older versions of Internet Explorer.
This helps reduce markup size without affecting compatibility-related comment blocks.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\Html\Comments(); $html = '<!-- regular comment --><div><!--[if IE]>keep<![endif]--></div>'; $modified = $modifier->modify($html); // '<div><!--[if IE]>keep<![endif]--></div>'
This modifier removes:
- Regular HTML comments such as
<!-- comment -->
It preserves:
- Conditional comments like
<!--[if IE]> ... <![endif]-->
Only non-conditional comments are stripped. All other HTML content remains untouched.
Doctype HTML Modifier
The Doctype modifier normalizes any existing HTML doctype declaration to the minimal HTML5 form.
This ensures consistent output and removes legacy or verbose doctypes without affecting the rest of the document.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\Html\Doctype(); $html = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"><html></html>'; $modified = $modifier->modify($html); // '<!DOCTYPE html><html></html>'
This modifier performs a single transformation:
- Replaces any doctype declaration with the minimal HTML5 doctype:
<!DOCTYPE html>
It does not modify any other part of the HTML document.
Whitespaces HTML Modifier
The Whitespaces modifier collapses redundant whitespace in HTML and removes unnecessary gaps between tags.
It reduces file size while keeping the document's structure and semantics intact.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\Html\Whitespaces(); $html = "<div> Hello </div> <span> World </span>"; $modified = $modifier->modify($html); // '<div> Hello </div><span> World </span>'
This modifier performs the following cleanups:
- Collapses multiple consecutive whitespace characters into a single space.
- Removes whitespace between HTML tags (
> <becomes><). - Trims leading and trailing whitespace from the entire document.
It does not alter text content inside tags beyond collapsing repeated spaces, and it does not modify tag structure or attributes.
JavaScript Modifiers
Comments JS Modifier
The Comments modifier removes JavaScript comments to reduce file size while preserving code behavior.
It removes full-line // comments and multi-line /* … */ comments without touching URLs, strings, template literals, or inline // sequences.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\JavaScript\Comments(); $js = "/* header */\n// setup\nvar x = 1;\nvar url = 'http://example.com';"; $modified = $modifier->modify($js); // "var x = 1;\nvar url = 'http://example.com';"
This modifier performs the following cleanups:
- Removes full-line single-line comments (lines that contain only
//comments, optionally preceded by whitespace) - Removes multi-line comments (
/* ... */) - Trims leading and trailing whitespace from the final output
It does not remove inline // comments and does not attempt to parse JavaScript syntax.
This ensures that URLs, strings, template literals, and regular expressions remain intact.
Whitespaces JS Modifier
The Whitespaces modifier normalizes and collapses unnecessary whitespace in JavaScript code.
It reduces file size by simplifying spacing and line breaks while preserving the overall structure of the code.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\JavaScript\Whitespaces(); $js = "var x = 1;\n\n console.log(x);"; $modified = $modifier->modify($js); // "var x = 1;\nconsole.log(x);"
This modifier performs the following cleanups:
- Collapses consecutive spaces and tabs into a single space (excluding line feeds)
- Removes leading and trailing whitespace around line breaks
- Collapses multiple blank lines into a single line break
- Normalizes leftover spacing patterns for a cleaner output
Important limitations
- This modifier does not parse JavaScript syntax.
- It may alter whitespace inside:
- string literals
- template literals
- regular expression literals
- It is therefore not safe for arbitrary or third-party JavaScript.
- It is intended for controlled codebases, such as your own project files where whitespace inside literals is not meaningful.
Generic Modifiers
Callable Modifier
The CallableModifier allows any PHP callable to be used as a minification modifier.
It acts as a lightweight wrapper that forwards the content to the provided callable and returns its result.
use Tobento\Service\Minify\Modifier; $modifier = new Modifier\CallableModifier(function (string $content) { return strtoupper($content); }); echo $modifier->modify('hello'); // 'HELLO'
This modifier performs the following behavior:
- Wraps any valid callable so it can be used as a modifier
- Passes the content string to the callable and returns the callable's output
- Ensures the provided value is callable and throws an exception otherwise
This is especially useful when integrating third-party minifiers or external processing functions.
Any existing minification logic can be plugged in directly without creating a dedicated modifier class.
The modifier itself applies no transformations. All behavior is defined by the user-supplied callable.
Custom Modifier
You can create your own modifier by implementing the ModifierInterface.
A custom modifier receives the content as a string and must return the modified result.
use Tobento\Service\Minify\ModifierInterface; class MyCustomModifier implements ModifierInterface { public function modify(string $content): string { // apply any transformation you need return str_replace('foo', 'bar', $content); } }
Custom modifiers are useful when you need project-specific transformations or want full control over how content is processed.
They integrate seamlessly with the minifier pipeline and can be combined with built-in modifiers.
If you prefer not to create a dedicated class, the Callable Modifier allows you to wrap any callable and use it as a modifier directly.
Factories
CSS Minifier Factory
The CssMinifierFactory creates a CSS Minifier instance composed of one or more
CSS modifiers. By default, it includes all built-in CSS modifiers, but the
modifier pipeline can be fully customized.
This factory allows you to:
- select only specific built-in modifiers
- exclude specific built-in modifiers
- append custom modifiers to the end of the pipeline
- prepend custom modifiers to run before all others
- combine built-in and custom modifiers in any order
Built-in modifier keys
The factory provides the following modifier keys:
charsetscolorscommentsfont-weightsleading-zeroquotessemicolonswhitespaceszero-unitszero-values
If no modifiers are specified, all of the above are enabled by default.
Usage example
use Tobento\Service\Minify\CssMinifierInterface; use Tobento\Service\Minify\Factory\CssMinifierFactory; // default: all modifiers enabled $factory = new CssMinifierFactory(); // or with specific modifiers only // $factory = new CssMinifierFactory(modifiers: ['comments']); // exclude comments and whitespaces $factory = $factory->except('comments', 'whitespaces'); // or use only the specified built-in modifiers $factory = $factory->only('leading-zero'); // append a custom modifier $factory = $factory->addModifier(new MyCustomCssModifier()); // or prepend one to run it before all others $factory = $factory->prependModifier(new MyCustomCssModifier()); // create the minifier $minifier = $factory->createMinifier(); var_dump($minifier instanceof CssMinifierInterface); // bool(true) $minified = $minifier->minify($css);
Customizing the modifier pipeline
-
only(...)
Defines exactly which built-in modifier keys should be used, replacing the current list. -
except(...)
Excludes one or more built-in modifier keys from the current list. -
addModifier(ModifierInterface)
Appends a custom modifier instance to the end of the pipeline. -
prependModifier(ModifierInterface)
Prepends a custom modifier instance to the beginning of the pipeline.
How it works
When createMinifier() is called:
- Each modifier entry is resolved:
- strings are mapped to built-in modifier classes
- instances of
ModifierInterfaceare used directly
- The resolved modifiers are assembled into a
Modifierspipeline - A CSS Minifier instance is returned
This design keeps the CSS minifier flexible, composable, and easy to extend with project-specific or third-party modifiers.
HTML Minifier Factory
The HtmlMinifierFactory creates an HTML Minifier instance composed of one or more
HTML modifiers. By default, all built‑in HTML modifiers are enabled, but the
modifier pipeline can be fully customized.
This factory allows you to:
- select only specific built-in modifiers
- exclude specific built-in modifiers
- append custom modifiers to the end of the pipeline
- prepend custom modifiers to run before all others
- combine built-in and custom modifiers in any order
Built-in modifier keys
The factory provides the following modifier keys:
attributescommentsdoctypewhitespaces
If no modifiers are specified, all of the above are enabled by default.
Usage example
use Tobento\Service\Minify\HtmlMinifierInterface; use Tobento\Service\Minify\Factory\HtmlMinifierFactory; // default: all modifiers enabled $factory = new HtmlMinifierFactory(); // or with specific modifiers only // $factory = new HtmlMinifierFactory(modifiers: ['comments']); // exclude comments and doctype $factory = $factory->except('comments', 'doctype'); // or use only the specified built‑in modifiers $factory = $factory->only('attributes'); // append a custom modifier $factory = $factory->addModifier(new MyCustomHtmlModifier()); // or prepend one to run it before all others $factory = $factory->prependModifier(new MyCustomHtmlModifier()); // create the minifier $minifier = $factory->createMinifier(); var_dump($minifier instanceof HtmlMinifierInterface); // bool(true) $minified = $minifier->minify($html);
Customizing the modifier pipeline
-
only(...)
Defines exactly which built-in modifier keys should be used, replacing the current list. -
except(...)
Excludes one or more built-in modifier keys from the current list. -
addModifier(ModifierInterface)
Appends a custom modifier instance to the end of the pipeline. -
prependModifier(ModifierInterface)
Prepends a custom modifier instance to the beginning of the pipeline.
How it works
When createMinifier() is called:
- Each modifier entry is resolved:
- strings are mapped to built-in modifier classes
- instances of
ModifierInterfaceare used directly
- The resolved modifiers are assembled into a
Modifierspipeline - A HTML Minifier instance is returned
This design keeps the HTML minifier flexible, composable, and easy to extend with project-specific or third-party modifiers.
JavaScript Minifier Factory
The JavaScriptMinifierFactory creates a JavaScript Minifier instance composed of one or more
JavaScript modifiers. By default, all built-in JavaScript modifiers are enabled, but the
modifier pipeline can be fully customized.
This factory allows you to:
- select only specific built-in modifiers
- exclude specific built-in modifiers
- append custom modifiers to the end of the pipeline
- prepend custom modifiers to run before all others
- combine built-in and custom modifiers in any order
Built-in modifier keys
The factory provides the following modifier keys:
commentswhitespaces
If no modifiers are specified, both built-in modifiers are enabled by default.
Usage example
use Tobento\Service\Minify\JavaScriptMinifierInterface; use Tobento\Service\Minify\Factory\JavaScriptMinifierFactory; // default: all modifiers enabled $factory = new JavaScriptMinifierFactory(); // or with specific modifiers only // $factory = new JavaScriptMinifierFactory(modifiers: ['comments']); // exclude comments $factory = $factory->except('comments'); // or use only the specified built-in modifiers $factory = $factory->only('whitespaces'); // append a custom modifier $factory = $factory->addModifier(new MyCustomJsModifier()); // or prepend one to run it before all others $factory = $factory->prependModifier(new MyCustomJsModifier()); // create the minifier $minifier = $factory->createMinifier(); var_dump($minifier instanceof JavaScriptMinifierInterface); // bool(true) $minified = $minifier->minify($js);
Customizing the modifier pipeline
-
only(...)
Defines exactly which built-in modifier keys should be used, replacing the current list. -
except(...)
Excludes one or more built-in modifier keys from the current list. -
addModifier(ModifierInterface)
Appends a custom modifier instance to the end of the pipeline. -
prependModifier(ModifierInterface)
Prepends a custom modifier instance to the beginning of the pipeline.
How it works
When createMinifier() is called:
- Each modifier entry is resolved:
- strings are mapped to built-in modifier classes
- instances of
ModifierInterfaceare used directly
- The resolved modifiers are assembled into a
Modifierspipeline - A JavaScript Minifier instance is returned
This design keeps the JavaScript minifier flexible, composable, and easy to extend with project-specific or third-party modifiers.
Null Minifier Factory
The NullMinifierFactory creates a Null Minifier instance.
This minifier performs no transformations on the input and simply returns the content unchanged.
This factory is useful when:
- minification should be disabled in certain environments (e.g., development)
- you want to explicitly bypass minification while keeping the same interface
- an asset handler expects a minifier but you do not want any processing applied
Usage example
use Tobento\Service\Minify\Factory\NullMinifierFactory; $factory = new NullMinifierFactory(); $minifier = $factory->createMinifier(); $original = $minifier->minify($content); // unchanged
How it works
When createMinifier() is called:
- A new
NullMinifierinstance is returned - The minifier simply returns the input content without modification
This design provides a simple, predictable way to disable minification while maintaining compatibility with the minifier pipeline and the asset handler system.
Minifiers
The Minifiers class acts as a registry and resolver for all available minifiers.
It allows you to register minifiers by name and retrieve them on demand.
A minifier may be:
- a
MinifierInterfaceinstance - a
MinifierFactoryInterfaceinstance (lazy-loaded) - a callable returning a
MinifierInterface(lazy-loaded)
If a requested minifier is not found, a fallback minifier is created using the
configured fallback factory (default: NullMinifierFactory).
Minifiers Registry
You may register any number of named minifiers:
use Tobento\Service\Minify\MinifierInterface; use Tobento\Service\Minify\Minifiers; use Tobento\Service\Minify\MinifiersInterface; use Tobento\Service\Minify\Factory; $minifiers = new Minifiers( minifiers: [ 'css' => new Factory\CssMinifierFactory(), 'html' => new Factory\HtmlMinifierFactory(), 'js' => fn() => new Factory\JavaScriptMinifierFactory()->createMinifier(), ], // Used as fallback if a named minifier is missing // minifierFactory: new Factory\NullMinifierFactory(), // default ); var_dump($minifiers instanceof MinifiersInterface); // bool(true) // Add minifiers in all supported ways: // 1. Direct instance $minifiers->add('direct', new Factory\CssMinifierFactory()->createMinifier()); // 2. Factory (lazy-loaded) $minifiers->add('factory', new Factory\CssMinifierFactory()); // 3. Callable (lazy-loaded) $minifiers->add( name: 'callable', minifier: fn(): MinifierInterface => new Factory\HtmlMinifierFactory()->createMinifier(), ); // Check if a minifier exists $minifiers->has('css'); // true or false // Retrieve a minifier $cssMinifier = $minifiers->get('css'); // List all registered minifier names: $minifiers->names(); // ['css', 'html', 'js']