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

Static Class Laravel Package

scriptfusion/static-class

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require scriptfusion/static-class
    

    Add the StaticClass trait to your class:

    use ScriptFUSION\StaticClass\StaticClass;
    
    class MyStaticClass
    {
        use StaticClass;
    
        public static function myStaticMethod()
        {
            return 'Hello, Static World!';
        }
    }
    
  2. First Use Case:

    • Use this trait to enforce static-only behavior in utility classes (e.g., StringHelper, ArrayHelper, Logger).
    • Example:
      $result = MyStaticClass::myStaticMethod(); // Works
      $instance = new MyStaticClass(); // Throws \RuntimeException
      
  3. Where to Look First:


Implementation Patterns

Common Workflows

  1. Enforcing Static Design:

    • Use in Laravel for classes that should never be instantiated (e.g., Config, Route, or custom helpers).
    • Example:
      class DatabaseHelper
      {
          use StaticClass;
      
          public static function sanitizeInput(string $input): string
          {
              return filter_var($input, FILTER_SANITIZE_STRING);
          }
      }
      
  2. Integration with Laravel:

    • Service Providers: Register static classes as facades or helpers.
      // app/Providers/AppServiceProvider.php
      public function boot()
      {
          app()->singleton('staticHelper', function () {
              return new class {
                  use StaticClass;
                  public static function greet() { return 'Laravel!'; }
              };
          });
      }
      
    • Facades: Create a facade for static classes (though facades are typically for singletons, this can work for static methods).
      // app/Facades/StaticHelper.php
      namespace App\Facades;
      use Illuminate\Support\Facades\Facade;
      class StaticHelper extends Facade
      {
          protected static function getFacadeAccessor() { return 'staticHelper'; }
      }
      
  3. Testing:

    • Mock static methods using partialMock in PHPUnit:
      $mock = $this->getMockBuilder(MyStaticClass::class)
          ->setMethods(['myStaticMethod'])
          ->getMock();
      $mock->method('myStaticMethod')->willReturn('Mocked!');
      

Extension Points

  • Custom Exceptions: Override the default RuntimeException by extending the trait:
    class CustomStaticClass
    {
        use StaticClass {
            __construct as private __staticConstruct;
        }
    
        public function __construct()
        {
            throw new \InvalidArgumentException('Cannot instantiate!');
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Instantiation Attempts:

    • The trait throws a RuntimeException if instantiation is attempted. Catch this explicitly in tests or edge cases:
      try {
          new MyStaticClass();
      } catch (\RuntimeException $e) {
          $this->assertStringContainsString('Cannot instantiate', $e->getMessage());
      }
      
  2. Static Method Limitations:

    • Static methods cannot access $this or instance properties. Design classes to avoid stateful logic.
    • Avoid static methods that rely on Laravel’s container (e.g., app()->make()) unless explicitly needed.
  3. Facade Confusion:

    • Facades are not static classes. Using this trait with facades may lead to unexpected behavior. Prefer facades for singletons and static classes for stateless utilities.

Debugging

  • Unexpected Instantiation:
    • If a static class is instantiated via reflection or serialization, the trait’s __construct() will still block it. Use debug_backtrace() to trace the origin:
      public function __construct()
      {
          throw new \RuntimeException(
              'Cannot instantiate ' . static::class .
              '. Called from: ' . print_r(debug_backtrace(), true)
          );
      }
      

Configuration Quirks

  • No Runtime Configuration:
    • The trait is purely behavioral with no runtime configuration. All enforcement is hardcoded in the __construct() method.

Extension Tips

  • Add Static Properties:

    • The trait allows static properties but doesn’t enforce their usage. Document whether static properties are permitted:
      class MathUtils
      {
          use StaticClass;
          private static $pi = 3.14159;
      
          public static function calculateCircleArea(float $radius): float
          {
              return self::$pi * pow($radius, 2);
          }
      }
      
  • Laravel-Specific Use:

    • Combine with Laravel’s ShouldBeStatic trait (if available) or use this trait in phpstan/psalm configurations to enforce static-only classes in static analysis tools. Example psalm.config.php:
      return [
          'properties' => [
              'ScriptFUSION\StaticClass\StaticClass' => [
                  'properties' => [],
              ],
          ],
      ];
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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