Back to Deck
[utility]
Tailwind PHP Trait
ИСХОДНИК PHP
ВЕРСИЯ 1.0
АВТОР Cododel
PHP Trait InteractsWithTailwind, предоставляющий fluent-методы для распространенных утилит Tailwind CSS. Изначально разработан как встраиваемый модуль для библиотек рендеринга HTML.
⚠️ Важное замечание
JIT компилятор Tailwind не парсит динамическую композицию классов подобным образом. Классы, сгенерированные программно, не будут обнаружены во время сканирования на этапе сборки, а значит не попадут в скомпилированный CSS без явного добавления в safelist.
Это делает модуль ограниченно полезным по сравнению с прямыми вызовами ->class("bg-blue-300"), которые Tailwind может обнаружить при сканировании PHP файлов.
Применение
Изначально планировалось для библиотеки рендеринга Table/Row/Cell:
Table::registerModule(Tailwind::class);
$table = Table::make([ Row::make([ Cell::make("Финансовый результат по видам деятельности") ->tailwind( fn(Tailwind $t) => $t ->bgBlue(300) ->textCenter() ) ->width(200) ->colSpan(2), Cell::make($contract_number), ]),]);Почему это проблематично
- Tailwind не детектирует
"text-red-$shade"при сканировании - Требуется ручная стилизация - нужно добавлять все возможные классы в safelist
- Есть лучшая альтернатива - прямые вызовы
->class()работают отлично
Когда может быть полезно
- Прототипирование с полным Tailwind CDN
- Проекты, где все классы явно добавлены в safelist
- Обучающий пример для fluent PHP API
Исходный код
InteractsWithTailwind.php
<?php
namespace App\Services\HTML\Modules\Tailwind;
trait InteractsWithTailwind{ abstract public function class(string $class): static;
// Text utilities public function bold() { return $this->class('font-bold'); } public function italic() { return $this->class('italic'); } public function underline() { return $this->class('underline'); } public function textCenter() { return $this->class('text-center'); } public function textLeft() { return $this->class('text-left'); } public function textRight() { return $this->class('text-right'); }
// Color utilities public function textRed($shade = 500) { return $this->class("text-red-$shade"); } public function textBlue($shade = 500) { return $this->class("text-blue-$shade"); } public function bgRed($shade = 500) { return $this->class("bg-red-$shade"); } public function bgBlue($shade = 500) { return $this->class("bg-blue-$shade"); }
// Margin and padding utilities public function p($size = 4) {return $this->class("p-$size"); } public function m($size = 4) { return $this->class("m-$size"); } public function px($size = 4) { return $this->class("px-$size"); } public function py($size = 4) { return $this->class("py-$size"); } public function mx($size = 4) { return $this->class("mx-$size"); } public function my($size = 4) { return $this->class("my-$size"); }
// Display utilities public function flex() { return $this->class('flex'); } public function grid() { return $this->class('grid'); } public function hidden() { return $this->class('hidden'); } public function block() { return $this->class('block'); } public function inlineBlock() { return $this->class('inline-block'); }
// Width and height utilities public function wFull() { return $this->class('w-full'); } public function hFull() { return $this->class('h-full'); } public function w($size) { return $this->class("w-$size"); } public function h($size) { return $this->class("h-$size"); }
// Border utilities public function border() { return $this->class('border'); } public function borderColor($color = 'gray-500') { return $this->class("border-$color"); } public function borderWidth($width = 1) { return $this->class("border-$width"); } public function rounded($size = 'md') { return $this->class("rounded-$size"); }
// Flexbox utilities public function justifyCenter() { return $this->class('justify-center'); } public function itemsCenter() { return $this->class('items-center'); } public function justifyBetween() { return $this->class('justify-between'); } public function itemsStart() { return $this->class('items-start'); }
// Position utilities public function absolute() { return $this->class('absolute'); } public function relative() { return $this->class('relative'); } public function fixed() { return $this->class('fixed'); } public function top($value) { return $this->class("top-$value"); } public function left($value) { return $this->class("left-$value"); }
// Shadow utilities public function shadow($size = 'md') { return $this->class("shadow-$size"); }}Tailwind.php (Модуль-обёртка)
<?php
namespace App\Services\HTML\Modules\Tailwind;
use App\Services\HTML\HTMLElement;use App\Services\HTML\Modules\Module;use Closure;
class Tailwind extends Module{ use InteractsWithTailwind; public $element;
public function __construct(HTMLElement $element) { $this->element = $element; }
public static function getModuleName(): string { return 'tailwind'; }
protected function class(string $class): static { $this->element->class($class); return $this; }
public static function getCallback(HTMLElement $element): callable { $instance = new static($element);
return function (string|Closure $arg) use ($instance) { if (is_callable($arg)) { $arg($instance); } else { $instance->class($arg); }
return $instance->element; }; }}