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

Apache Mime Types Laravel Package

dflydev/apache-mime-types

Parse and query Apache mime.types mappings in PHP. Includes bundled Apache mime.types plus JSON representation. Use parser to read mime.types files, or repositories (PHP, JSON, flat) to look up MIME type by extension and extensions by type.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dflydev/apache-mime-types
    

    Add to composer.json if not using autoloading:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Dflydev\\ApacheMimeTypes\\": "vendor/dflydev/apache-mime-types/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Quickly determine a file's MIME type or extensions for a given type:

    use Dflydev\ApacheMimeTypes\PhpRepository;
    
    $repository = new PhpRepository();
    $type = $repository->findType('php'); // Returns 'text/x-php'
    $extensions = $repository->findExtensions('text/html'); // Returns ['html', 'htm']
    

Where to Look First

  • PhpRepository: Pre-loaded with Apache's mime.types (no parsing needed).
  • JsonRepository: Useful if you need a custom JSON-backed MIME map.
  • Parser: Only needed if you must parse a custom mime.types file.

Implementation Patterns

Core Workflows

  1. File Uploads: Validate file types before processing:

    $repository = new PhpRepository();
    $allowedTypes = ['image/jpeg', 'image/png'];
    $fileExt = strtolower(pathinfo($request->file('avatar')->getClientOriginalName(), PATHINFO_EXTENSION));
    $actualType = $repository->findType($fileExt);
    
    if (!in_array($actualType, $allowedTypes)) {
        throw new \InvalidArgumentException("Invalid file type.");
    }
    
  2. Dynamic Content Negotiation: Serve assets based on Accept headers:

    $repository = new PhpRepository();
    $preferredType = $request->header('Accept');
    $extensions = $repository->findExtensions($preferredType);
    
    // Return the first available extension (e.g., for fallback logic)
    $extension = $extensions[0] ?? 'default';
    
  3. Custom MIME Maps: Extend JsonRepository for project-specific mappings:

    $customJson = json_encode([
        'application/vnd.myapp+json' => ['myapp', 'mya']
    ]);
    $repository = new JsonRepository($customJson);
    

Integration Tips

  • Laravel Filesystem: Combine with Storage facade for MIME-aware file handling:

    use Illuminate\Support\Facades\Storage;
    
    $path = $request->file('file')->store('uploads');
    $mime = new PhpRepository();
    $type = $mime->findType(pathinfo($path, PATHINFO_EXTENSION));
    Storage::disk('s3')->put($path, Storage::get($path), ['mime_type' => $type]);
    
  • Validation Rules: Create reusable validation logic:

    use Dflydev\ApacheMimeTypes\PhpRepository;
    
    $mimeRepo = new PhpRepository();
    $validator = Validator::make($request->all(), [
        'file' => ['required', 'mimes:' . implode(',', $mimeRepo->findExtensions('image/jpeg'))]
    ]);
    
  • Service Providers: Bind the repository as a singleton for dependency injection:

    $this->app->singleton(PhpRepository::class, function ($app) {
        return new PhpRepository();
    });
    

Gotchas and Tips

Pitfalls

  1. Case Sensitivity: Extensions are case-sensitive in the repository. Normalize inputs:

    $extension = strtolower($request->file('file')->getClientOriginalExtension());
    
  2. Missing Types: Not all extensions/types are covered. Handle fallbacks:

    $type = $repository->findType('unknown_ext') ?: 'application/octet-stream';
    
  3. Parser Overhead: Avoid using Parser in production unless necessary—it’s slower than PhpRepository or JsonRepository.

  4. JSON Repository Pitfalls:

    • Ensure JSON is valid before passing to JsonRepository.
    • No auto-refresh: JSON data is static; reload manually if updated externally.

Debugging

  • Verify Data: Dump the raw repository data to debug:

    $repository = new PhpRepository();
    dd($repository->getAllTypesAndExtensions());
    
  • Check for Typos: Use findType() or findExtensions() to validate keys:

    if (empty($repository->findType('php'))) {
        // Likely a typo or missing entry.
    }
    

Extension Points

  1. Custom Parsing: Extend Parser to handle non-standard mime.types formats:

    class CustomParser extends Parser {
        protected function parseLine($line) { /* Override logic */ }
    }
    
  2. Hybrid Repository: Combine multiple repositories (e.g., Apache + custom JSON):

    class HybridRepository implements RepositoryInterface {
        public function findType($extension) {
            $apacheRepo = new PhpRepository();
            $customRepo = new JsonRepository($customJson);
            return $apacheRepo->findType($extension) ?: $customRepo->findType($extension);
        }
    }
    
  3. Caching: Cache repository results for performance (e.g., in Laravel’s app service provider):

    $this->app->singleton(PhpRepository::class, function () {
        return new PhpRepository(); // Already cached by Composer autoloader.
    });
    

Config Quirks

  • No Runtime Configuration: The package is self-contained—no config/ or .env settings. All behavior is code-driven.
  • Default Data: PhpRepository uses bundled Apache data. To override, use JsonRepository with your own JSON.
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium