Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow overriding default implementation of TemporaryDirectory #1846

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

jonerickson
Copy link

@jonerickson jonerickson commented Sep 29, 2024

This PR arises out of the need to change the default implementation of the TemporaryDirectory service. In our story, serving a multi-tenant application and using this package to backup each individual tenant's DB, we needed the ability to customize the temporary directory's location. Because we have a large number of tenants, we elected to create a batch job to backup each tenant's DB. Because of this, we are running into the issue where multiple jobs are trying to use the same temporary directory. As you can imagine, this creates chaos. We now have the ability to set the file path based on the current tenant context allowing each tenant to use their own temporary directory.

Extending the implementation:

$this->app->extend(TemporaryDirectory::class, function (TemporaryDirectoryAdapter $temporaryDirectory) {
    return new TenantTemporaryDirectory($temporaryDirectory);
});

Customizing our tmp path:

class TenantTemporaryDirectory extends TemporaryDirectory implements TemporaryDirectoryContract
{
    public function __construct(TemporaryDirectory $temporaryDirectory)
    {
        parent::__construct($temporaryDirectory->location);
    }

    protected function getFullPath(): string
    {
        if (! tenancy()->initialized) {
            return parent::getFullPath();
        }

        $tenantId = tenant()->getTenantKey();

        return storage_path(optional($tenantId, fn ($id) => "app/backup-temp/tenant$id") ?? 'app/backup-temp').DIRECTORY_SEPARATOR.$this->name;
    }
}

@jonerickson jonerickson marked this pull request as draft September 29, 2024 22:00
@jonerickson jonerickson marked this pull request as ready for review October 1, 2024 03:12
@jonerickson
Copy link
Author

Hey Spatie team, seeing if you have any questions regarding this PR. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant