Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Twig Php Function Laravel Package

umpirsky/twig-php-function

Lightweight Twig extension that lets you call any PHP function directly from your templates with a simple php_function() call. Skip writing custom Twig extensions for quick formatting, hashing, or utility helpers. Works with Twig 2 and 3.

Deep Wiki
Context7

Getting Started

  • Install via Composer:
    composer require umpirsky/twig-php-function
    
  • If you're using Laravel with TwigBridge, register the extension in config/twigbridge.php under the extensions key:
    'extensions' => [
        // ...
        Umpirsky\Twig\Extension\PhpFunctionExtension::class,
    ],
    
    Then clear config cache: php artisan config:clear.
  • For standalone Twig:
    $twig->addExtension(new \Umpirsky\Twig\Extension\PhpFunctionExtension());
    
  • The extension exposes a single Twig function named php. First use case: quick formatting in a template without writing a custom filter:
    {{ php('ucwords', user.name) }}
    {{ php('number_format', product.price, 2) }}
    {{ php('date', 'Y-m-d', order.createdAt.timestamp) }}
    
  • Look first at vendor/umpirsky/twig-php-function/src/PhpFunctionExtension.php. The README is minimal; the source is small and tells you exactly how arguments are forwarded and what exceptions are thrown.

Implementation Patterns

  • One-off utility calls: Use php() for simple string, array, or number transformations where a dedicated Twig filter feels heavy.
    {{ php('array_slice', items, 0, 3) | join(', ') }}
    
  • Static helper methods: call_user_func_array supports Class::method, so you can route complex logic to a static helper and keep templates readable.
    {{ php('App\\Support\\Format::currency', amount, currency) }}
    
  • Nested calls: Compose functions, but keep nesting shallow. If you need more than two levels, promote the logic to a Twig filter or a view model.
    {% set slug = php('strtolower', php('str_replace', ' ', '-', title)) %}
    
  • Variadic arguments: All trailing arguments are passed through, so sprintf and similar functions work naturally.
    {{ php('sprintf', '%s (%s)', name, code) }}
    
  • Conditional logic: Use it inside {% if %} for checks Twig lacks.
    {% if php('in_array', role, ['admin', 'owner']) %}
    
    For repeated checks, prefer a custom Twig test.
  • TwigBridge integration: Once registered, php() is available in every .twig file. No manual filter registration is needed unless you want a different function name.
  • Escape hatch, not a foundation: Treat php() as a bridge for edge cases. For common operations (dates, money, slugs), write a dedicated Twig filter or function so you get a stable, testable API and better security.

Gotchas and Tips

  • Security: This extension exposes every callable PHP function to your templates. Never use it with user-editable templates. Even with developer-controlled templates, avoid passing user input directly to dangerous functions (exec, system, file_put_contents, etc.). To restrict the surface, subclass PhpFunctionExtension and override call() with an allow-list.
  • Autoescaping: Twig escapes the return value by default. If a PHP function returns HTML (e.g., nl2br), you must add |raw, which reintroduces XSS risk. Prefer functions that return plain text or escape manually.
  • Functions that output directly: var_dump, print_r, and printf write to output and return null/true. The side-effect output appears before the escaped return value, potentially breaking your layout. Avoid them or wrap them in output buffering inside a helper.
  • By-reference parameters: call_user_func_array does not preserve references for parameters like the third argument of preg_match or the array in sort. Calls may fail or behave unexpectedly. Test before relying on them.
  • Missing functions: If a function doesn't exist or is disabled via disable_functions, the extension throws a RuntimeException. Verify with php -r 'var_dump(function_exists("your_function"));' and check php.ini.
  • Twig compatibility: Older versions of this package may target Twig 1/2. If you're on Twig 3, confirm the extension class extends Twig\Extension\AbstractExtension. If not, you may need a shim or an updated fork.
  • TwigBridge config cache: After adding the extension, run php artisan config:clear (and view:clear if needed). If php() is undefined, the extension isn't registered or the config is cached.
  • Performance: Each call performs a function_exists check and a call_user_func_array. Negligible for typical templates, but avoid calling inside tight loops over large collections; precompute in the controller or a view composer.
  • Extension points: The class is small. You can extend it to add a whitelist, log calls, or expose a safer alias (e.g., safe_php) that only allows a curated list. You can also register it conditionally based on the environment.
  • No object methods: The extension calls functions and static methods only. To call an instance method, pass the object to a custom Twig function or use a filter.
  • Debugging: If you get a blank output, check whether the function returns null or outputs directly. With Twig debug enabled, use {{ dump(php('strtoupper', 'test')) }} to inspect the return value.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
mrnewport/laravel-plaid
mrnewport/laravel-repo
mrnewport/laravel-docsign
mrnewport/laravel-stow
mrnewport/laravel-flow
mrnewport/laravel-priceable
mrnewport/laravel-nestedterms
fredmeng/laravel-apidoc-generator
itstructure/laravel-multilingual-tools
pdustdar/elasticsearch
markupai/php-sdk
rlacerda83/lumem-microservice-shipment
uni-method/symfony-lib
tacticmedia/scim-server-bundle
neika-ai/symfony-bundle
mattleads/agent-publishing-bundle
glavweb/framework-bundle
glavweb/extra-bundle
glavweb/api-bundle
glavweb/admin-bundle