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 Helpers Laravel Package

andreas-glaser/php-helpers

PHP 8.2+ helper toolkit offering ArrayHelper and other utilities for everyday tasks. Includes dot-notation get/set/unset, key/value lookups, insert/prepend/append, random/first/last helpers, filtering empty values, implode/explode helpers, key casing conversion, and more.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Update to v2.0.0 via Composer:

    composer require andreas-glaser/php-helpers:^2.0
    

    No additional configuration is required—it’s a standalone library with backward-compatible additions.

  2. First Use Case Import and use new helpers directly in Laravel controllers or services:

    use AndreasGlaser\Helpers\RequestHelper;
    use AndreasGlaser\Helpers\UrlHelper;
    
    // Example: Detect request type
    if (RequestHelper::isAjax()) {
        return response()->json(['status' => 'success']);
    }
    
    // Example: Parse URL
    $domain = UrlHelper::getDomain('https://sub.example.com/path');
    
  3. Key Entry Points (Updated)

    • HTTP Request Analysis: RequestHelper (e.g., isMobile(), getUserAgent()).
    • URL Manipulation: UrlHelper (e.g., addQuery(), normalize()).
    • Network Utilities: NetworkHelper (e.g., isValidIp(), getPublicIp()).
    • Enhanced HTML Generation: AttributesHelper (e.g., create() with validation).
    • Legacy Helpers: StringHelper, ArrayHelper, DateTimeHelper (unchanged).

    Where to Look First: Browse the updated README for v2.0.0’s comprehensive examples or check the src/Helpers directory for new classes.


Implementation Patterns

Common Workflows

  1. HTTP Request Analysis Replace Laravel’s Request facade with RequestHelper for cross-cutting concerns:

    // Middleware: Block bots
    if (RequestHelper::isBot()) {
        abort(403);
    }
    
    // Controller: Mobile detection
    if (RequestHelper::isMobile()) {
        return view('mobile.home');
    }
    
  2. URL Manipulation Use UrlHelper for dynamic URL generation in services:

    // Add query params to a URL
    $url = UrlHelper::addQuery('https://example.com', [
        'filter' => 'active',
        'page' => 2,
    ]);
    
    // Parse domain/subdomain
    $subdomain = UrlHelper::getSubdomain('https://blog.example.com');
    
  3. Network Operations Leverage NetworkHelper for IP validation or DNS lookups:

    // Validate IP in a request
    if (!NetworkHelper::isValidIp(request('ip'))) {
        return back()->withErrors(['ip' => 'Invalid format']);
    }
    
    // Get public IP (useful for proxied requests)
    $ip = NetworkHelper::getPublicIp();
    
  4. HTML Generation Use AttributesHelper for immutable HTML attribute creation:

    // Safe attribute generation
    $attrs = AttributesHelper::create([
        'class' => 'btn btn-primary',
        'data-toggle' => 'modal',
        'disabled' => true,
    ])->toString();
    
  5. Integration with Laravel

    • Service Providers: Bind new helpers for global access:
      $this->app->singleton('requestHelper', function () {
          return new \AndreasGlaser\Helpers\RequestHelper();
      });
      
    • Blade Directives: Extend Blade with new helpers:
      Blade::directive('isMobile', function () {
          return "<?php echo \\AndreasGlaser\\Helpers\\RequestHelper::isMobile() ? 'mobile' : 'desktop'; ?>";
      });
      
      Usage: @isMobile.
  6. Testing Mock new helpers in PHPUnit:

    $this->partialMock(RequestHelper::class, ['isAjax'])
        ->expects($this->once())
        ->method('isAjax')
        ->willReturn(true);
    

Gotchas and Tips

Pitfalls

  1. Namespace Collisions (Unchanged)

    • Prefix new helpers to avoid conflicts:
      use AndreasGlaser\Helpers\RequestHelper as HelpersRequest;
      
  2. CLI Detection Edge Case

    • RequestHelper::isCli() may return false during PHPUnit execution. Use Laravel’s app()->runningInConsole() as a fallback:
      if (RequestHelper::isCli() || app()->runningInConsole()) {
          // CLI logic
      }
      
  3. URL Normalization Quirks

    • UrlHelper::normalize() trims trailing slashes by default. Override with:
      UrlHelper::normalize('https://example.com/', false); // Preserves trailing slash
      
  4. NetworkHelper Limitations

    • DNS lookups (NetworkHelper::resolve()) block execution. Use in async jobs or queues:
      dispatch(new ResolveDnsJob($domain));
      
  5. AttributesHelper Immutability

    • Methods like AttributesHelper::create() return immutable instances. Chain methods:
      $attrs = AttributesHelper::create(['class' => 'btn'])
          ->add('data-test', 'true')
          ->toString();
      

Debugging Tips

  1. Enable Error Reporting Add to config/app.php:

    'providers' => [
        AndreasGlaser\Helpers\HelpersServiceProvider::class,
    ],
    

    For silent failures, log helper outputs:

    Log::debug('Request type', ['type' => RequestHelper::getRequestType()]);
    
  2. Validate URLs Before Use Use UrlHelper::isValid() to catch malformed URLs early:

    if (!UrlHelper::isValid($userInputUrl)) {
        Log::warning('Invalid URL provided', ['url' => $userInputUrl]);
    }
    
  3. Fallback to Native PHP For unsupported edge cases (e.g., complex IP ranges), fall back to PHP’s built-ins:

    $ipValid = filter_var($ip, FILTER_VALIDATE_IP) !== false;
    

Extension Points

  1. Custom Request Helpers Extend RequestHelper for project-specific logic:

    class CustomRequestHelper extends \AndreasGlaser\Helpers\RequestHelper {
        public static function isInternalRequest(): bool {
            return str_contains(request()->ip(), '192.168.');
        }
    }
    
  2. URL Strategy Patterns Create URL builders using UrlHelper:

    class ApiUrlBuilder {
        public static function build(string $endpoint, array $params = []): string {
            return UrlHelper::addQuery(
                config('app.api_url') . $endpoint,
                $params
            );
        }
    }
    
  3. Network Middleware Use NetworkHelper in middleware for IP-based rules:

    public function handle($request, Closure $next) {
        if (NetworkHelper::isPrivateIp($request->ip())) {
            abort(403);
        }
        return $next($request);
    }
    
  4. Test-Driven Development Leverage the new test suite to validate custom extensions:

    // Test a custom URL helper
    public function testCustomUrlBuilder() {
        $url = ApiUrlBuilder::build('/users', ['role' => 'admin']);
        $this->assertEquals(
            'https://api.example.com/users?role=admin',
            $url
        );
    }
    
  5. Performance Optimization Cache RequestHelper results for repeated checks:

    $isMobile = cache()->remember('request.is_mobile', now()->addHours(1), function () {
        return RequestHelper::isMobile();
    });
    
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.
terminal42/code-quality-tools
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