Weave Code
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

Php To String Laravel Package

coduo/php-to-string

Convert any PHP value to a readable string with a tiny wrapper. Supports strings, ints, floats, arrays, objects, callables, and resources—handy for logging, debugging, and error messages. Simple install and use: new StringConverter($value).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require coduo/php-to-string
    

    No configuration is required—just autoload the package.

  2. First Use Case Convert any PHP value to a string with a single method call:

    use Coduo\PHPToString\PHPToString;
    
    $value = PHPToString::toString(new DateTime());
    // Output: "2025-12-02T12:00:00+00:00"
    
    $value = PHPToString::toString(['key' => 'value']);
    // Output: "Array ( [key] => value )"
    
  3. Where to Look First

    • Core Class: PHPToString (handles all conversions).
    • Tests: tests/ for edge cases (e.g., null, objects, resources).
    • Custom Rules: CustomRules for extending behavior.

Implementation Patterns

Core Workflows

  1. Basic Conversion Replace var_export() or (string) casts with explicit control:

    $string = PHPToString::toString($object);
    // More reliable than (string)$object for complex types.
    
  2. Laravel Integration

    • Model Attributes: Use in AppServiceProvider to serialize model data for logs/APIs:
      public function boot()
      {
          Model::macro('toString', function ($attribute = null) {
              return PHPToString::toString($attribute ?? $this->toArray());
          });
      }
      
    • Request Validation: Sanitize user input before storage:
      $cleanedInput = collect($request->all())
          ->map(fn ($value) => PHPToString::toString($value));
      
  3. Debugging/Logging Replace dd() or Log::debug() with structured strings:

    Log::debug('User data', [
        'raw' => PHPToString::toString($user),
        'sanitized' => PHPToString::toString($user->only(['name', 'email']))
    ]);
    
  4. Custom Formatters Extend for domain-specific needs (e.g., pretty-printing collections):

    PHPToString::addRule(
        Collection::class,
        fn (Collection $collection) => $collection->toJson()
    );
    

Gotchas and Tips

Pitfalls

  1. Resource Handling

    • Resources (e.g., file handles) throw RuntimeException. Use get_resource_type() to check first:
      if (is_resource($value)) {
          return 'Resource of type: ' . get_resource_type($value);
      }
      
  2. Circular References

    • Objects with circular references (e.g., self-referencing properties) may cause infinite loops. Use PHPToString::toString($obj, 0) to limit depth.
  3. Performance

    • Avoid converting large arrays/objects repeatedly. Cache results if used in loops:
      $cache = [];
      $string = $cache[$obj->id] ?? ($cache[$obj->id] = PHPToString::toString($obj));
      

Debugging Tips

  • Inspect Rules: List all registered rules to debug unexpected output:
    PHPToString::getRules(); // Returns associative array of [type => formatter]
    
  • Override Defaults: Disable built-in rules for specific types:
    PHPToString::removeRule(DateTime::class);
    

Extension Points

  1. Custom Rules Register formatters for your classes:

    PHPToString::addRule(
        MyCustomClass::class,
        fn (MyCustomClass $obj) => "Custom: {$obj->id}"
    );
    
  2. Global Configuration Set default options (e.g., max depth) via static properties:

    PHPToString::$maxDepth = 2; // Limit recursion depth.
    
  3. Laravel Facade Create a facade for cleaner syntax:

    // app/Providers/AppServiceProvider.php
    PHPToString::macro('toString', fn ($value) => PHPToString::toString($value));
    

    Now use:

    use App\PHPToString as PTS;
    PTS::toString($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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor