Ga naar de inhoud

API

Het volledige statische oppervlak staat op één klasse: TailwindPHP\tw (een alias van de interne klasse Tailwind). Elke methode kan statisch worden aangeroepen, en de inspectiemethoden (properties, computedProperties, value, computedValue) accepteren allemaal de invoerformaten die onderaan deze pagina worden beschreven.

Voor herhaald werk met dezelfde CSS-configuratie roept u tw::compile() één keer aan en hergebruikt u de geretourneerde TailwindCompiler.

PHP
use TailwindPHP\tw;

$css = tw::generate('<div class="flex items-center p-4 bg-blue-500">');

tw::generate()

PHP
public static function generate(string|array $input, string $css = '@import "tailwindcss";'): string

Parseert inhoud, haalt klassekandidaten eruit en retourneert de gegenereerde CSS. De standaardwaarde van $css is @import "tailwindcss";, die thema, preflight en hulpfuncties toevoegt. Retourneert string.

PHP
use TailwindPHP\tw;

// String input
$css = tw::generate('<div class="flex p-4">');

// String with custom CSS
$css = tw::generate('<div class="flex bg-brand">', '@import "tailwindcss"; @theme { --color-brand: #3b82f6; }');

// Array input with options
$css = tw::generate([
    'content' => '<div class="flex p-4">',
    'css' => '@import "tailwindcss";',
    'minify' => true,
]);

De arrayvorm accepteert deze sleutels:

Sleutel Type Doel
content string Inhoud waarin naar klassekandidaten wordt gezocht (vereist)
css string CSS-invoer met Tailwind-richtlijnen (standaard @import "tailwindcss";)
minify bool De uitvoer minificeren (standaard false)
importPaths string | array | callable | null CSS uit het bestandssysteem laden met volledige @import-resolutie — zie Importeren van CSS
cache bool | string Bestandsgebaseerde caching inschakelen — zie Caching
cacheTtl int Levensduur van de cache in seconden

tw::compile()

PHP
public static function compile(string $css = '@import "tailwindcss";', array $options = []): TailwindCompiler

Maakt een herbruikbare TailwindCompiler aan die aan de opgegeven CSS is gekoppeld. Het parsen en opbouwen van het designsysteem gebeurt één keer, dus dit is de efficiënte keuze wanneer u voor veel verschillende inhoudsstrings CSS genereert. Gebruik generate() om bij elke aanroep één stylesheet aan te vullen, of generateExact() voor onafhankelijke uitvoer per pagina. Retourneert TailwindCompiler.

PHP
use TailwindPHP\tw;

// Default Tailwind
$compiler = tw::compile();

// Custom CSS
$compiler = tw::compile('@import "tailwindcss"; @theme { --color-brand: #3b82f6; }');

$css = $compiler->generate('<div class="flex p-4 bg-brand">');

De $options-array accepteert:

Optie Type Doel
stateCacheFile string Pad naar een PHP-bestand dat de constructiestatus van de compiler bewaart tussen aanvragen en processen door — zie Cache voor compilerstatus
polyfills int Welke fallbacks moeten worden gegenereerd, als bitmasker van TailwindPHP\POLYFILL_AT_PROPERTY (de @layer properties-standaardwaarden voor @property-variabelen) en TailwindPHP\POLYFILL_COLOR_MIX (statische kleurfallbacks vóór color-mix()). Standaard POLYFILL_ALL; POLYFILL_NONE schakelt beide uit
importSearchPaths array<string> Mappen waarin wordt gezocht naar @import op het bestandssysteem
PHP
use TailwindPHP\tw;
use const TailwindPHP\POLYFILL_NONE;

// Cache construction state on disk, reused by later requests
$compiler = tw::compile('@import "tailwindcss";', [
    'stateCacheFile' => __DIR__ . '/cache/tailwind-state.php',
]);

// Plain output without fallbacks, e.g. for CSS modules
$compiler = tw::compile('@import "tailwindcss/utilities.css";', [
    'polyfills' => POLYFILL_NONE,
]);
$compiler->generate('<div class="bg-red-500/50">');
// .bg-red-500\/50 { background-color: color-mix(in oklab, var(--color-red-500) 50%, transparent); }
// (with the default, a `#fb2c3680` fallback comes first and color-mix() moves into @supports)

Zie Instantiemethoden van TailwindCompiler voor alle methoden van de instantie.

tw::properties()

PHP
public static function properties(string|array $input, string $css = '@import "tailwindcss";'): array

Retourneert de onbewerkte CSS-eigenschappen voor een klasse, waarbij CSS-variabelen onopgelost blijven. Retourneert array<string, string> (eigenschapsnaam → waarde).

PHP
use TailwindPHP\tw;

tw::properties('p-4');
// ['padding' => 'calc(var(--spacing) * 4)']

tw::properties(['flex', 'items-center', 'p-4']);
// ['display' => 'flex', 'align-items' => 'center', 'padding' => 'calc(var(--spacing) * 4)']

tw::computedProperties()

PHP
public static function computedProperties(string|array $input, string $css = '@import "tailwindcss";'): array

Net als properties(), maar dan met alle variabelen van CSS opgelost naar concrete waarden. Retourneert array<string, string>.

PHP
use TailwindPHP\tw;

tw::computedProperties('p-4');
// ['padding' => '1rem']

tw::computedProperties('text-blue-500');
// ['color' => 'oklch(62.3% .214 259.815)']

tw::computedProperties(['flex', 'items-center', 'gap-4']);
// ['display' => 'flex', 'align-items' => 'center', 'gap' => '1rem']

tw::value()

PHP
public static function value(string|array $input, string $css = '@import "tailwindcss";'): ?string

Retourneert de onbewerkte waarde voor één hulpprogrammaklasse. Retourneert ?string — null als de utility niet wordt gevonden.

PHP
use TailwindPHP\tw;

tw::value('p-4');           // 'calc(var(--spacing) * 4)'
tw::value('text-blue-500'); // 'var(--color-blue-500)'

tw::computedValue()

PHP
public static function computedValue(string|array $input, string $css = '@import "tailwindcss";'): ?string

Retourneert de opgeloste waarde voor één hulpprogrammaklasse. Retourneert ?string — null als de utility niet wordt gevonden.

PHP
use TailwindPHP\tw;

tw::computedValue('p-4');           // '1rem'
tw::computedValue('text-blue-500'); // 'oklch(62.3% .214 259.815)'
tw::computedValue('gap-4');         // '1rem'

tw::extractCandidates()

PHP
public static function extractCandidates(string $html): array

Haalt Tailwind-klassenamen uit inhoud (leest zowel de attributen class als className). Retourneert array<string>.

PHP
use TailwindPHP\tw;

tw::extractCandidates('<div class="flex p-4" className="bg-blue-500">');
// ['flex', 'p-4', 'bg-blue-500']

tw::extractCandidatesFromStrings()

PHP
public static function extractCandidatesFromStrings(string $source): array

Haalt kandidaten voor klassenamen uit elke string tussen enkele of dubbele aanhalingstekens in de broncode, voor templates die klasselijsten opbouwen in variabelen in plaats van in class-attributen. Elke string wordt op witruimte gesplitst en elk token dat op een klassenaam lijkt, wordt behouden. Retourneert array<string>.

PHP
use TailwindPHP\tw;

$classes = tw::extractCandidatesFromStrings('<?php $wrap = \'p-4 sm:flex\'; $title = "hello world"; ?>');
// ['p-4', 'sm:flex', 'hello', 'world']

$css = tw::compile()->css($classes);

Ook gewone woorden doorstaan de controle (hierboven: hello, world); ze worden tot niets gecompileerd, tenzij ze toevallig utilitynamen zijn. Geef het resultaat door aan css(), want generate() leest alleen attributen class.

tw::cssMap()

PHP
public static function cssMap(string $css = '@import "tailwindcss";'): array

Bouwt een omgekeerde koppeling op van CSS-declaraties naar utilityklassen, handig om bestaande CSS om te zetten naar Tailwind-klassen. De sleutels zijn "property: value"-strings met opgeloste variabelen (utilities met meerdere eigenschappen krijgen ook een sleutel "prop: value; prop: value"); de waarden zijn klassennamen. Retourneert array<string, string>.

PHP
use TailwindPHP\tw;

$map = tw::cssMap();
$map['display: flex'];       // 'flex'
$map['padding: 1rem'];       // 'p-4'
$map['text-align: center'];  // 'text-center'
$map['color: #fff'];         // 'text-white'

De koppeling omvat een vaste lijst met veelgebruikte utilities (display, position, flexbox, typografie, stappen voor spatiëring en afmetingen, randen, zwart, wit en transparante kleuren, en vergelijkbare waarden), niet elke utility of themakleur. Het argument $css wijzigt de opgeloste waarden van die utilities, maar aangepaste thematokens (zoals --color-brand) voegen geen items toe.

tw::minify()

PHP
public static function minify(string $css): string

Minificeert een willekeurige CSS-string: verwijdert opmerkingen, voegt witruimte samen, verkort hexkleuren (#ffffff → #fff), verwijdert eenheden bij nulwaarden (0px → 0) en meer. Retourneert string.

Voor CSS die TailwindPHP zelf genereert, gebruikt u bij voorkeur de optie minify (tw::generate(['minify' => true])) of de parameter $minify bij de compilermethoden. Hierbij wordt tijdens het serialiseren geminificeerd, wat sneller is en onderliggende :not()-selectors behoudt die de stringgebaseerde stap samenvoegt.

PHP
use TailwindPHP\tw;

$css = tw::generate('<div class="flex p-4">');
$minified = tw::minify($css);

Zie Caching en minificatie voor alle optimalisaties.

tw::clearCache()

PHP
public static function clearCache(string|bool|null $cache = true): int

Verwijdert gecachete CSS-bestanden. Geef true (of niets) op voor de standaardcachemap, of een pad als u een aangepaste map wilt gebruiken. Retourneert int — het aantal verwijderde bestanden.

PHP
use TailwindPHP\tw;

tw::clearCache();                  // default directory
tw::clearCache('/path/to/cache');  // custom directory

Er is ook een zelfstandige TailwindPHP\clearCache()-functie beschikbaar.

tw::colors()

PHP
public static function colors(string $css = '@import "tailwindcss";'): array

Retourneert alle kleurwaarden uit het thema. Retourneert array<string, string> (kleurnaam → berekende waarde).

PHP
use TailwindPHP\tw;

tw::colors();
// ['red-500' => 'oklch(63.7% .237 25.331)', 'blue-500' => 'oklch(62.3% .214 259.815)', ...]

// With a custom theme
tw::colors('@import "tailwindcss"; @theme { --color-brand: #3b82f6; }');
// [..., 'brand' => '#3b82f6']

tw::breakpoints()

PHP
public static function breakpoints(string $css = '@import "tailwindcss";'): array

Retourneert alle breakpointwaarden uit het thema. Retourneert array<string, string> (breakpointnaam → waarde).

PHP
use TailwindPHP\tw;

tw::breakpoints();
// ['sm' => '40rem', 'md' => '48rem', 'lg' => '64rem', 'xl' => '80rem', '2xl' => '96rem']

tw::breakpoints('@import "tailwindcss"; @theme { --breakpoint-xs: 20rem; }');
// ['sm' => '40rem', ..., '2xl' => '96rem', 'xs' => '20rem']

tw::spacing()

PHP
public static function spacing(string $css = '@import "tailwindcss";'): array

Retourneert aangepaste spatiëringswaarden uit het thema. Retourneert array<string, string> (spatiëringsnaam → waarde).

PHP
use TailwindPHP\tw;

// TailwindCSS 4 uses a single --spacing base value rather than a --spacing-* namespace.
// This returns any custom --spacing-* values defined in the theme.
tw::spacing('@import "tailwindcss"; @theme { --spacing-huge: 10rem; }');
// ['huge' => '10rem']

Invoerformaten

De inspectiemethoden (generate, properties, computedProperties, value, computedValue) accepteren drie invoervormen:

Formaat Voorbeeld
Alleen een string tw::generate('<div class="flex">')
String + CSS-string tw::generate('<div class="flex">', '@import "tailwindcss"; @theme { ... }')
Array met content (+ optioneel css) tw::generate(['content' => '<div class="flex">', 'css' => '@import "tailwindcss";'])
PHP
use TailwindPHP\tw;

// Format 1: string only
tw::properties('p-4');

// Format 2: string + CSS
tw::properties('bg-brand', '@import "tailwindcss"; @theme { --color-brand: #3b82f6; }');

// Format 3: array
tw::properties(['content' => 'p-4', 'css' => '@import "tailwindcss";']);

Instant Methoden van TailwindCompiler

Het object dat door tw::compile() wordt geretourneerd, biedt dezelfde inspectiemethoden als de statische klasse, gekoppeld aan de CSS waarmee het is gecompileerd. Zo hoeft het thema niet bij elke aanroep opnieuw te worden geparseerd.

PHP
public function generate(string $content, bool $minify = false): string
public function css(array $candidates, bool $minify = false): string
public function generateExact(string $content, bool $minify = false): string
public function cssExact(array $candidates, bool $minify = false): string
public function extractCandidates(string $html): array
public function extractCandidatesFromStrings(string $source): array
public function properties(string|array $utilities): array
public function computedProperties(string|array $utilities): array
public function value(string $utility): ?string
public function computedValue(string $utility): ?string
public function minify(string $css): string
public function colors(): array
public function breakpoints(): array
public function spacing(): array
PHP
use TailwindPHP\tw;

$compiler = tw::compile('@import "tailwindcss"; @theme { --color-brand: #3b82f6; }');

$css        = $compiler->generate('<div class="flex p-4 bg-brand">');
$candidates = $compiler->extractCandidates('<div class="flex p-4 bg-brand">');

$compiler->properties('bg-brand');          // ['background-color' => 'var(--color-brand)']
$compiler->computedProperties('bg-brand');   // ['background-color' => '#3b82f6']
$compiler->value('bg-brand');                // 'var(--color-brand)'
$compiler->computedValue('bg-brand');        // '#3b82f6'

$minified = $compiler->minify($css);

$compiler->colors();        // all color values
$compiler->breakpoints();   // all breakpoint values
$compiler->spacing();       // custom spacing values

Opbouwend tegenover exact genereren

generate() en css() bouwen op: elke aanroep voegt kandidaten toe aan de groeiende verzameling van de compiler, en de geretourneerde stylesheet omvat alles wat tot dan toe is gezien. Dat is geschikt voor één stylesheet die over meerdere templates wordt opgebouwd.

generateExact() en cssExact() compileren per aanroep precies de opgegeven inhoud of kandidaten, zonder gegevens tussen aanroepen mee te nemen, terwijl het geparseerde designsysteem van de compiler wel wordt hergebruikt. De uitvoer komt overeen met die van een koude tw::generate() van dezelfde inhoud. Dit is de snelste manier om per pagina CSS te maken met één compiler die lang actief blijft:

PHP
use TailwindPHP\tw;

$compiler = tw::compile($themeCss);

foreach ($pages as $slug => $html) {
    $perPageCss[$slug] = $compiler->generateExact($html, true);
}

Alle vier methoden accepteren een optionele vlag $minify die tijdens het serialiseren geminificeerde CSS oplevert, byte voor byte identiek aan tw::generate(['minify' => true]) en efficiënter dan de opgemaakte uitvoer achteraf minificeren.

Geavanceerde inspecteurs

Om de gecompileerde status rechtstreeks te inspecteren:

PHP
public function getTheme(): Theme
public function getDesignSystem(): object
public function getCompiled(): array
PHP
$compiler->getTheme();        // Theme object with resolved values
$compiler->getDesignSystem(); // Design system: utilities, variants, etc.
$compiler->getCompiled();     // Raw compiled state array

Deze retourneren interne structuren; zie Architectuur voor de inhoud ervan.

Functies op lager niveau

De klasse tw omvat een set functies met een namespace in TailwindPHP. Ze zijn handig wanneer u het onbewerkte compilatieresultaat nodig hebt in plaats van een TailwindCompiler:

Functie Doel
compile(string $css, array $options = []): array Parseert en compileert CSS. Retourneert build (opbouwend) en buildExact-closures die kandidaten en een optionele vlag $minify accepteren, plus sources, root, features en designSystem. Accepteert dezelfde opties als tw::compile(), behalve stateCacheFile
StateCache\compileCssCached(string $css, string $cacheFile, array $options = []): array compile() met de blijvende cache voor compilerstatus
parseCssState(), finalizeCssState(), compileParsed() De twee fasen van het parsen (een serialiseerbare status, gevolgd door de daaruit opnieuw opgebouwde closures) en de laatste assemblagestap die compileCssCached() gebruikt. parseCss() en compileAst() blijven de tegenhangers die alles in één stap doen
PHP
use function TailwindPHP\compile;

$compiled = compile('@import "tailwindcss";');
$css = $compiled['build'](['flex', 'p-4'], true); // minified

Caching

tw::generate() kan gecompileerde CSS op schijf cachen, zodat identieke invoer niet opnieuw hoeft te worden gecompileerd.

Optie Type Standaard Doel
cache bool | string false true schakelt de standaardmap in; een pad slaat de cache daar op
cacheTtl int geen Levensduur van de cache in seconden; verlopen items worden opnieuw gecompileerd
PHP
use TailwindPHP\tw;

// Default directory: sys_get_temp_dir() . '/tailwindphp'
$css = tw::generate([
    'content' => '<div class="flex p-4">',
    'cache' => true,
]);

// Custom directory + TTL
$css = tw::generate([
    'content' => '<div class="flex p-4">',
    'cache' => '/path/to/cache',
    'cacheTtl' => 3600, // expire after 1 hour
]);

De cachecode wordt afgeleid van de inhoud, de CSS-configuratie en de optie minify, zodat verschillende invoer verschillende cachebestanden oplevert. Wis items met tw::clearCache() of met de zelfstandige functie TailwindPHP\clearCache().

Zie Caching en minificatie voor de uitgebreide uitleg.