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

Merged
merged 5 commits into from
Jan 13, 2025

Conversation

jonerickson
Copy link
Contributor

@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
Contributor Author

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

src/BackupServiceProvider.php Outdated Show resolved Hide resolved
@jonerickson jonerickson force-pushed the feature/bind-temp-service branch from 2eb117c to 885de52 Compare January 10, 2025 02:15
@freekmurze freekmurze merged commit 234dc8a into spatie:main Jan 13, 2025
1 check passed
@freekmurze
Copy link
Member

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.

2 participants