KnpGaufretteBundle Documentation

repository·master·Indexed 20 days ago

https://github.com/knplabs/knpgaufrettebundle

A Symfony integration for Gaufrette, a PHP filesystem abstraction library. It allows developers to manage media files using a consistent API across various storage backends, including Local, AWS S3 (SDK v2, v3, and AsyncAws), Azure Blob Storage, FTP, SFTP, and APC. The bundle provides configuration for adapters and filesystems, a filesystem map service for retrieving Gaufrette\Filesystem instances, and a CLI command to list file keys.

Tokens
11.8K
Snippets
49
Records
56
Agent score
72%

What's inside KnpGaufretteBundle

  1. Use the Gaufrette Stream Wrapper

    master

    The stream_wrapper feature allows you to register your configured Gaufrette filesystems as PHP stream wrappers. Once registered, you can access files using a URI format like protocol://domain/path/to/file.txt. This enables you to use standard PHP filesystem functions (like file_get_contents, fopen, etc.) directly with your Gaufrette filesystems.

    gaufrette://domain/file.txt
  2. Use the Cache adapter to wrap other adapters

    master

    The cache adapter allows you to wrap an existing adapter (the source) with a caching layer. This is useful for improving performance when using slow adapters like FTP or S3. When a filesystem uses a cached adapter, it first checks the cache before falling back to the source adapter.

    Parameters

    ParameterDescription
    source(Required) The name of the source adapter that you want to cache.
    cache(Required) The name of the adapter used to store the cached data (e.g., an APC or Redis adapter).
    ttlTime to live for the cached items, in seconds. Defaults to 0.
    serializerThe adapter used to handle serializations. Defaults to null.
    # app/config/config.yml
    knp_gaufrette:
        adapters:
            media_ftp:
                ftp:
                    host: example.com
                    username: user
                    password: pass
                    directory: /example/ftp
                    create: true
                    mode: FTP_BINARY
            media_apc:
                apc:
                    prefix: APC 'namespace' prefix
                    ttl: 0
            media_cache:
                cache:
                    source: media_ftp
                    cache: media_apc
                    ttl: 7200
        filesystems:
            media:
                adapter: media_cache
  3. Use the In-Memory adapter for testing

    master

    The in_memory adapter is designed for testing purposes. Instead of interacting with a real filesystem, it stores files in an internal array.

    You can pre-populate the adapter with files by providing a files array in your configuration. Each file entry is a sub-array that can optionally include content, checksum, and mtime (modification time).

    # app/config/config.yml
    knp_gaufrette:
        adapters:
            foo:
                in_memory:
                    files:
                        'file1.txt':    ~
                        'file2.txt':
                            content:    Some content
                            checksum:   abc1efg2hij3
                            mtime:      123456890123
  4. Use the Safe Local Adapter

    master

    The safe_local adapter is a variation of the standard local adapter that encodes keys to prevent issues with directory structures. It is useful when you want to store files in a local directory but want the library to handle the creation of nested subdirectories automatically based on encoded keys, avoiding direct manipulation of the filesystem hierarchy.

    # app/config/config.yml
    knp_gaufrette:
        adapters:
            foo:
                safe_local:
                    directory:  /path/to/my/filesystem
                    create:     true
  5. Create a Google Cloud Storage service factory

    master

    Because the Google Cloud adapter requires a \Google\Service\Storage instance, you must define a custom factory service in Symfony. This factory is responsible for initializing the \Google\Client, setting the appropriate scopes (e.g., \Google\Service\Storage::DEVSTORAGE_FULL_CONTROL), and returning the \Google\Service\Storage object.

    Note: It is recommended to use Symfony's service container features rather than hardcoding credentials directly in the factory.

    <?php
    
    namespace Appactory;
    
    class GoogleCloudStorageServiceFactory
    {
        public static function createGoogleCloudStorage()
        {
            $keyFileLocation = '/path/to/key/project-id.json';
            // ... setup logic ...
            putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $keyFileLocation);
            $client = new \Google\Client();
            $client->setApplicationName('Gaufrette');
            $client->addScope(\Google\Service\Storage::DEVSTORAGE_FULL_CONTROL);
            $client->useApplicationDefaultCredentials();
    
            return new \Google\Service\Storage($client);
        }
    }
  6. Configure the Doctrine DBAL adapter

    master

    The Doctrine DBAL adapter allows you to store file data directly into a database table. You must specify the Doctrine connection name and map the internal Gaufrette fields (key, content, mtime, and checksum) to your specific database column names.

    # app/config/config.yml
    knp_gaufrette:
        adapters:
            database:
                doctrine_dbal:
                    connection_name: default
                    table: data
                    columns:
                        key: id
                        content: text
                        mtime: date
                        checksum: checksum
  7. Configure the AWS S3 Adapter (Amazon SDK v2)

    master

    For projects using the older Amazon SDK v2, follow these steps:

    1. Install the SDK: Run composer require aws/aws-sdk-php:^2.0.
    2. Define the S3 Client Service: Register the Aws\S3\S3Client in your Symfony services configuration.
    3. Configure Gaufrette: Reference the service ID in your knp_gaufrette configuration.

    The parameters available for the aws_s3 adapter are identical to the v3 version.

    composer require aws/aws-sdk-php:^2.0
    # 1. Service definition
    services:
        acme.aws_s3.client:
            class: Aws\S3\S3Client
            factory: [Aws\S3\S3Client, 'factory']
            arguments:
                -
                    key: %amazon_s3.key%
                    secret: %amazon_s3.secret%
                    region: %amazon_s3.region%
    
    # 2. Gaufrette configuration
    knp_gaufrette:
        adapters:
            profile_photos:
                aws_s3:
                    service_id: 'acme.aws_s3.client'
                    bucket_name: 'images'
                    detect_content_type: true
                    options:
                        directory: 'profile_photos'
  8. Upload a file with adapter-specific logic

    master

    To upload a file, inject the knp_gaufrette.filesystem service (if using a single filesystem) or retrieve the specific filesystem from the knp_gaufrette.filesystem_map service.

    If you need to perform operations that are not part of the generic Gaufrette API—such as setting specific metadata for an AWS S3 bucket—you can retrieve the underlying adapter using $filesystem->getAdapter() and check its type using instanceof.

    /** @var AwsS3 $adapter */
    $adapter = $this->filesystem->getAdapter();
    
    // Example: Setting metadata specifically for the AwsS3 adapter
    if ($adapter instanceof AwsS3) {
        $adapter->setMetadata($filename, ['contentType' => 'application/pdf']);
    }
    
    $adapter->write($myAbsolutePath, file_get_contents($tempPath));
  9. Configure the APC adapter

    master

    The APC adapter is a non-persistent filesystem adapter. It is suitable for development environments or demo sites where data does not need to persist between requests.

    You can configure it under the knp_gaufrette.adapters section in your Symfony configuration. It requires a prefix to act as a namespace for the APC storage.

    # app/config/config.yml
    knp_gaufrette:
        adapters:
            foo:
                apc:
                    prefix: 'my_app_namespace.'
                    ttl: 0
  10. Configure the Local Filesystem Adapter

    master

    The Local Adapter allows you to use a local filesystem as a storage backend. You can define an adapter named foo (or any other name) under the knp_gaufrette.adapters configuration key.

    Required parameters:

    • directory: The absolute path to the directory of the filesystem.

    Optional parameters:

    • create: A boolean indicating whether the directory should be created automatically if it does not exist. Defaults to true.
    # app/config/config.yml
    knp_gaufrette:
        adapters:
            foo:
                local:
                    directory:  /path/to/my/filesystem
                    create:     true
  11. Configure the AWS S3 Adapter (Amazon SDK v3)

    master

    To use Amazon S3 with Gaufrette using the recommended SDK v3, follow these steps:

    1. Install the SDK: Run composer require aws/aws-sdk-php:^3.0.
    2. Define the S3 Client Service: Register the Aws\S3\S3Client in your Symfony services configuration using its factory method.
    3. Configure Gaufrette: Reference the service ID in your knp_gaufrette configuration.

    Note: Ensure your bucket is located in the correct region. S3 bucket names containing dots (e.g., com.mycompany.bucket) may cause issues with some SDK versions; using hyphens (e.g., com-mycompany-bucket) is safer.

    composer require aws/aws-sdk-php:^3.0
    # 1. Service definition
    services:
        acme.aws_s3.client:
            class: Aws\S3\S3Client
            factory: [Aws\S3\S3Client, 'factory']
            arguments:
                -
                    version: latest
                    region: %amazon_s3.region%
                    credentials:
                        key: %amazon_s3.key%
                        secret: %amazon_s3.secret%
    
    # 2. Gaufrette configuration
    knp_gaufrette:
        adapters:
            profile_photos:
                aws_s3:
                    service_id: 'acme.aws_s3.client'
                    bucket_name: 'images'
                    detect_content_type: true
                    options:
                        directory: 'profile_photos'
  12. Configure the Phpseclib SFTP adapter

    master

    To use the Phpseclib SFTP adapter, you must define the adapter in your Gaufrette configuration and provide a service ID that points to a configured phpseclib\Net\SFTP (or phpseclib\Net\SFTP for phpseclib 1.x) instance.

    Available configuration parameters:

    • phpseclib_sftp_id: The ID of the service that provides SFTP access.
    • directory: The remote directory to use (defaults to null).
    • create: Whether to create the directory if it does not exist (defaults to false).
    # app/config/config.yml
    knp_gaufrette:
        adapters:
            foo:
                phpseclib_sftp:
                    phpseclib_sftp_id: acme_test.sftp
                    directory: /example/sftp
                    create: true