PHP code example of rasuvaeff / yii3-filestorage

1. Go to this page and download the library: Download rasuvaeff/yii3-filestorage library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rasuvaeff / yii3-filestorage example snippets


// config/common/di/filestorage.php — the one binding the family does NOT
// provide: the physical store is your deployment's choice.
StoreInterface::class => static fn (StreamFactoryInterface $streams): StoreInterface
    => new FileSystemStore(
        name: 'upload',
        rootPath: '/app/runtime/upload',
        streamFactory: $streams,
    ),

// Optional: record image dimensions into File::$metadata on upload.
StorageInterface::class => static fn (Storage $storage): StorageInterface
    => new ImageMetadataStorage($storage),

// config/common/params.php — group policies (core), tables (-db), presets (-images)
return [
    'rasuvaeff/yii3-filestorage' => [
        'policies' => [
            '*' => ['maxBytes' => 20_971_520],
            'avatar' => ['allowedMimeTypes' => ['image/png', 'image/jpeg'], 'maxBytes' => 2_097_152],
        ],
    ],
    'rasuvaeff/yii3-filestorage-db' => [
        'fileTable' => 'filestorage_file',
        'blobTable' => 'filestorage_blob',
        'blobReservationTable' => 'filestorage_blob_reservation',
        'tablePrefix' => '',
    ],
    'rasuvaeff/yii3-filestorage-images' => [
        'presets' => [
            'thumb' => ['version' => 1, 'width' => 200, 'height' => 200, 'fit' => 'cover', 'format' => 'webp'],
        ],
    ],
];

// config/common/routes.php
Route::get('/files/{token}')->action(FileDownloadAction::class),
Route::post('/avatars')->action(fn (FileUploadAction $action) => $action), // group from wiring

// config/common/di/db-migration.php — the family's migrations register by
// namespace (yiisoft/db-migration ^2.1; see the -db README)
MigrationService::class => [
    'setSourceNamespaces()' => [['Rasuvaeff\\Yii3FilestorageDb\\Migration']],
],

// config/common/di/filestorage.php
use Psr\Http\Message\StreamFactoryInterface;
use Rasuvaeff\Yii3Filestorage\Repository\RepositoryInterface;
use Rasuvaeff\Yii3Filestorage\Store\FileSystem\FileSystemStore;
use Rasuvaeff\Yii3Filestorage\Store\StoreInterface;
use Rasuvaeff\Yii3Filestorage\Test\MemoryRepository;

return [
    StoreInterface::class => static fn (StreamFactoryInterface $streams): StoreInterface
        => new FileSystemStore(
            name: 'upload',
            rootPath: '/app/runtime/upload',
            streamFactory: $streams,
        ),

    // Development only — every record is lost when the process ends.
    RepositoryInterface::class => MemoryRepository::class,
];

use Rasuvaeff\Yii3Filestorage\StorageInterface;
use Rasuvaeff\Yii3Filestorage\Upload;

// From an HTTP upload.
$file = $storage->add(
    Upload::fromUploadedFile($request->getUploadedFiles()['avatar'], $streamFactory),
    groupName: 'avatars',
);

// From something your application generated — a rendered PDF, an export.
$file = $storage->add(
    Upload::fromStream($pdfStream, 'invoice-2026-08.pdf', $streamFactory),
    groupName: 'documents',
    description: 'August invoice',
    metadata: ['invoiceId' => 4711],
);

// From a path.
$file = $storage->add(Upload::fromPath('/tmp/import.csv', $streamFactory));

// From an RFC 2397 data URL — rich-text editors, JSON APIs, mobile clients.
$file = $storage->add(Upload::fromDataUrl(
    'data:image/png;base64,' . $base64Payload,
    'logo.png',
    $streamFactory,
    $clientHint, // the URL's media type claim, by reference — a hint, not a fact
));

$file = $storage->find($id);

$repository->save($file->withMetadata(
    [...$file->metadata, 'width' => 320, 'height' => 200],
    $clock->now(),
));

use Rasuvaeff\Yii3Filestorage\GroupFiles;

foreach ((new GroupFiles($repository, 'avatars'))() as $file) { /* ... */ }

// Or only those whose metadata carries a key — "every image we know the size of".
foreach ((new GroupFiles($repository, 'avatars', metadataKey: 'width'))() as $file) { /* ... */ }

$file = $storage->find($id);

$stream = $storage->stream($file);   // PSR-7, the default read path
$bytes  = $storage->content($file);  // capped; throws ContentTooLargeException
$there  = $storage->exists($file);   // are the bytes still physically there

$url = $storage->urlFor($file);                    // the one to call
$url = $storage->urlFor($file, $expiresAt);        // explicit expiry

// config/common/params.php
return [
    'rasuvaeff/yii3-filestorage' => [
        'defaultGroup' => 'common',
        'policies' => [
            'avatars' => [
                'allowedMimeTypes' => ['image/jpeg', 'image/png', 'image/webp'],
                'maxBytes' => 5_242_880,
                'maxPixels' => 40_000_000,
                '

final readonly class QuotaStorage implements StorageInterface
{
    public function __construct(private StorageInterface $inner, private Quotas $quotas) {}

    public function add(Upload $upload, ?string $groupName = null, /* … */): File
    {
        $this->quotas->assertRoom($upload->size());

        return $this->inner->add($upload, $groupName, /* … */);
    }

    // … delegate the rest
}

// config/common/di/filestorage.php
use Rasuvaeff\Yii3Filestorage\Storage;
use Rasuvaeff\Yii3Filestorage\StorageInterface;

return [
    StorageInterface::class => static fn (Storage $inner, Quotas $quotas): StorageInterface
        => new QuotaStorage($inner, $quotas),
];

$store = new InMemoryStore('test', $streamFactory, new StaticClock($now));
$storage = new Storage(
    stores: new StoreRegistry([$store]),
    repository: new MemoryRepository(),
    // …
);

$file = $storage->add(Upload::fromStream($stream, 'a.txt', $streamFactory));

Assert::same($store->writeCount(), 1);
Assert::same($store->bytesAt($file->relativePath), 'hello');

// config/console-maintenance/di/filestorage.php — the unscoped skeleton:
// same stores, same repository, NO FileScopeProviderInterface binding.
// A store that can list AND delete objects: gc --orphans --apply walks it
// and calls deleteObject() on each orphan — a read-only binding cannot sweep.
StoreInterface::class => /* the production store, with listing + deletion */,
RepositoryInterface::class => /* the -db repository */,
// FileScopeProviderInterface: deliberately NOT bound here.

// config/console-maintenance/params.php (or your entry script's bootstrap):
// run `./yii filestorage:check` first — it must print "Single-scope".