SlideShare a Scribd company logo
Filesystem Management
with Flysystem
Mark Niebergall
👏 Thank you!
• Organisers
• Delegates
• Speakers
• Sponsors
- Nucleus Security
🧑💻 PHP Community
• You are amazing
• Attending a conference
- Learn
- Network
- Have fun
- Apply what you learned
🧑💻 PHP Community
• You made it to Thursday afternoon! 🤯
• 🙋 Poll: Who is already using Flysystem?
Filesystem Management with Flysystem at PHP UK 2023
https://img
fl
ip.com/i/779qzd
🤔 Question
• How do you e
ff
ectively manage
fi
les with code?
🤔 Question
• Common solution
- fopen
-
fi
le_get_contents
-
fi
le_put_contents
- delete
- chmod
https://img
fl
ip.com/i/778h2c
AwsS3Service
Local
In Memory
AWS S3
Azure
SFTP
File
LocalService
InMemoryService
AzureService
SftpService
😵💫 The Problem
• “Flysystem is a
fi
le storage library for PHP. It provides one
interface to interact with many di
ff
erent types of
fi
lesystems. When you use Flysystem, you’re not only
protected from vendor lock-in, you’ll also have a
consistent experience for which ever storage is right for
you.”
Flysystem
Local
In Memory
AWS S3
Azure
SFTP
File
✅ Objective
• Familiarity with Flysystem API
• Ideas on implementation
• Improved
fi
lesystem interactions
📋 Overview
• Adapters
• Flysystem API
• Implementation Strategies
• Testing
Adapters
https://gifer.com/en/EgDb
Adapters
• Traditional
- Di
ff
erent code for local vs external
- Di
ff
erent code for each adapter
Adapters
• Use case
- Local for development
- SFTP for QA
- S3 storage for Production
Adapters
• Use case
- Variety of
fi
le types
Adapters
public function readLocal(string $location): string
{
return file_get_contents($location);
}
public function readS3(string $location): string
{
// read file from S3 storage
return 'File Contents';
}
public function getContents(string $storage, string $location): string
{
return match ($storage) {
'local' => $this->readLocal($location),
'awss3' => $this->readS3($location),
default => throw new InvalidArgumentException('Not configured'),
};
}
Adapters
• Flysystem is con
fi
gurable
- Local
- External services
Adapters
• O
ffi
cial Adapters - Local
- Local
- InMemory
Adapters
• O
ffi
cial Adapters - External
- AWS S3
- AsyncAws S3
- Azure Blob Storage
- Google Cloud Storage
- SFTP
- WebDAV
Adapters
• Community Adapters
- GitLab
Adapters
• Decorators
- Read-Only
‣ $adapter = new
InMemoryFilesystemAdapter();
$readOnlyAdapter = new
LeagueFlysystemReadOnlyReadOnlyFile
systemAdapter($adapter);
$filesystem = new Filesystem($adapter);
Adapters
• Decorators
- Path Pre
fi
xing
‣ $pathPrefixedAdapter = new
LeagueFlysystemPathPrefixngPathPref
ixedAdapter($adapter, 'a/path/prefix');
Flysystem API
http://www.quickmeme.com/meme/3uywoc
Flysystem API
• Decent documentation online
- https://
fl
ysystem.thephpleague.com/docs/
- Make sure you are on the correction version of
documentation!
Flysystem API
• Exists
- fileExists(string $location): bool
- directoryExists(string $location): bool
- has(string $location): bool
‣ $this->adapter->fileExists(
$path
)
|| $this->adapter->directoryExists(
$path
);
Flysystem API
• File CRUD
- C: Write
- R: Read
- U: Move
- D: Delete
Flysystem API
• Write
- write(
string $location,
string $contents,
array $config = []
): void
- writeStream(
string $location,
$contents,
array $config = []
): void
Flysystem API
• Read
- read(string $location): string
- readStream(string $location)
Flysystem API
• Delete
- delete(string $location): void
- deleteDirectory(string $location): void
Flysystem API
• Directory
- createDirectory(
string $location,
array $config = []
): void
- listContents(
string $location,
bool $deep = self::LIST_SHALLOW
): DirectoryListing
Flysystem API
• Files
- move(
string $source,
string $destination,
array $config = []
): void
- copy(
string $source,
string $destination,
array $config = []
): void
Flysystem API
• Metadata
- lastModified(string $path): int
- fileSize(string $path): int
- mimeType(string $path): string
- checksum(
string $path,
array $config = []
): string
Flysystem API
• Permissions
- setVisibility(
string $path,
string $visibility
): void
- visibility(string $path): string
Flysystem API
• URLs
- S3, Azure, Google Cloud, WebDAV
‣ publicUrl(
string $path,
array $config = []
): string
‣ temporaryUrl(
string $path,
DateTimeInterface $expiresAt,
array $config = []
): string
Flysystem API
• Frameworks
- Bundled with Laravel
- Available with Symfony
- Can be used with other frameworks too
Implementation Strategies
https://makeameme.org/meme/and-then-we-5b7d94
Implementation Strategies
• Con
fi
guration
• Exception Handling
• Wrapper
• Mount Manager
Implementation Strategies
• Con
fi
guration
- Injectable con
fi
guration for adapters
'filesystem' => [
'local' => [
'directory' => '/tmp/filesystem/files/',
],
'awss3' => [
'client' => [
'credentials' => [
'key' => 'key...',
'secret' => 'secret...',
],
'region' => 'us‑west‑1',
'version' => 'latest',
],
'bucket' => 'my-bucket-name',
],
],
Implementation Strategies
• Con
fi
guration
- Application
fl
exibility
- Variety of sources
‣ Database
‣ PHP con
fi
guration
fi
les
Implementation Strategies
• Con
fi
guration
- UI interface to con
fi
gure
- Scalability
Implementation Strategies
• Exception Handling
- Generic exception
‣ FilesystemException
- Speci
fi
c exceptions
‣ UnableToReadFile
‣ UnableToWriteFile
‣ UnableToDeleteFile
‣ UnableToCheckExistence
‣ ...
Implementation Strategies
• Exception Handling
- Full list of exceptions
‣ https://
fl
ysystem.thephpleague.com/docs/usage/
fi
lesystem-api/
Implementation Strategies
• Exception Handling
1. Catch Flysystem speci
fi
c exceptions
2. Handle the exception
3. Throw own meaningful exception
Implementation Strategies
public function read(string $location): string
{
try {
$contents = $this->filesystem->read($location);
} catch (UnableToReadFile $exception) {
// handle unable to read exception
// throw an exception
} catch (FilesystemException $exception) {
// handle general error
// throw an exception
}
return $contents;
}
Implementation Strategies
• Wrapper
- Wrapper or Facade Pattern
- Abstracts away underlying package
- Swappable package
- Unit testable
Implementation Strategies
• Wrapper
- Useful pattern for many services
‣ Filesystem
‣ Email
‣ SMS
‣ Database
‣ Queue system
Implementation Strategies
class FileStorageService
{
public function __construct(
protected Filesystem $filesystem
) {}
public function read(string $location): string
{
return $this->filesystem->read($location);
}
Implementation Strategies
• Mount Manager
- Scenario
‣ Retrieve
fi
les from an external service
‣ Write locally for processing
Implementation Strategies
• Mount Manager
- Scenario
‣ Move
fi
les between external adapters upon an event
Implementation Strategies
• Mount Manager
- Scenario
‣ Many customers
‣ Reports created, stored locally
‣ Reports delivered based on con
fi
guration
‣ Variety of
fi
le storage locations
Implementation Strategies
• Mount Manager
- Interact with
fi
les in many storage services
- Specify adapter in location
‣ awss3://subfolder/
fi
le.txt
‣ local://path/to/
fi
le.txt
MountManager
Local
In Memory
AWS S3
Azure
SFTP
Implementation Strategies
Implementation Strategies
class FileManager
{
public function __construct(
protected MountManager $mountManager
) {}
public function read(string $location): string
{
return $this->mountManager->read($location);
}
Implementation Strategies
class FileManagerFactory
{
public function __construct(
protected FileStorageAdapterFactory $adapterFactory
) {}
public function create(array $mounts): FileManager
{
$mountManageConfig = [];
foreach ($mounts as $storage => $config) {
$mountManageConfig[$storage] = new Filesystem(
$this->adapterFactory->create($storage, $config)
);
}
return new FileManager(new MountManager($mountManageConfig));
}
Implementation Strategies
class FileStorageAdapterFactory
{
public function create(string $adapter, array $config): FilesystemAdapter
{
return match ($adapter) {
'awss3' => new AwsS3V3Adapter($config['client'], $config['bucket']),
'local' => new LocalFilesystemAdapter($config['directory']),
};
}
Testing
https://img
fl
ip.com/i/7ami3u
Testing
• Historically problematic testing
fi
le interactions
- Test
fi
les
- Inject
fi
le content
- git ignore directory for testing
fi
les
- Skip testing that code
- Integration tests vs Unit tests
Testing
public function testRead(): void
{
$file = __DIR__ . '/TestingFile.txt';
$service = new FileStorageLocalLegacyService();
$contents = $service->read($file);
$this->assertSame(
'Test file contents 123 ...',
$contents
);
}
Testing
• Flysystem abstraction layer allows for testing
- Mock calls to
fi
le interactions
- Pushes for single purpose code
- Centralized
fi
lesystem management
Testing
public function testRead(): void
{
$text = 'Test text!';
$testPath = uniqid('/tmp/test/') . '.txt';
$filesystemMock = $this->getMockBuilder(Filesystem::class)
->disableOriginalConstructor()
->onlyMethods(['read'])
->getMock();
$filesystemMock->method('read')
->with($testPath)
->willReturn($text);
$service = new FileStorageService($filesystemMock);
$contents = $service->read($testPath);
$this->assertSame($text, $contents);
}
🗣 Discussion
🗣 Discussion
• Bene
fi
ts of Flysystem?
• Cons of Flysystem?
🗣 Discussion
• Security
• Credentials
🗣 Discussion
• Conversion cost
• Scalability
• Maintenance
📋 Review
• External Services
• Flysystem API
• Implementation Strategies
• Testing
Mark Niebergall @mbniebergall
• PHP since 2005
• Masters degree in MIS
• Senior Software Engineer
• Vulnerability Management project (security scans)
• Utah PHP Co-Organizer
• CSSLP, SSCP Certi
fi
ed and Exam Developer
• Endurance sports, outdoors
Mark Niebergall @mbniebergall
Mark Niebergall @mbniebergall
Filesystem Management with Flysystem
• Questions?
• I’ll stay after to answer more questions, help with setup
and con
fi
gs
👀 References
• https://
fl
ysystem.thephpleague.com/docs/usage/
fi
lesystem-api/
• https://github.com/thephpleague/
fl
ysystem

More Related Content

PPTX
Olap vs oltp bases datos 2
DOCX
Cuestionario jefe inventario
PPTX
Base de Dato Oracle
PPT
Sistema De Gestion De Notas De Post Grado
PPTX
Objeto SqlDataAdapter
PPTX
Normas ieee 1100 1999
PPTX
CRUD html php mysql
PDF
Filesystem Management with Flysystem - php[tek] 2023
Olap vs oltp bases datos 2
Cuestionario jefe inventario
Base de Dato Oracle
Sistema De Gestion De Notas De Post Grado
Objeto SqlDataAdapter
Normas ieee 1100 1999
CRUD html php mysql
Filesystem Management with Flysystem - php[tek] 2023

Similar to Filesystem Management with Flysystem at PHP UK 2023 (20)

PDF
Filesystems Lisbon 2018
PDF
Filesystem Abstraction with Flysystem
PDF
PyFilesystem
PPTX
PHP deployment, 2016 flavor - cakefest 2016
PPTX
Filesystem abstractions and msg queue sergeev - symfony camp 2018
PDF
An Enhanced Cloud Backed Frugal File System
PDF
Hybrid Cloud PHPUK2012
PDF
Scaling PHP apps
PDF
Midwest php 2013 deploying php on paas- why & how
PDF
Hopping in clouds - phpuk 17
KEY
Anatomy of a high-volume, cloud-based WordPress architecture
PDF
Develop and deploy using Hybrid Cloud Strategies confoo2012
PPTX
PHP deploy 2015 flavor - talk from php tour 2015 luxembourg
PPTX
File Context
PDF
OSDC 2010 | Use Distributed Filesystem as a Storage Tier by Fabrizio Manfred
PPTX
Microservices and Best Practices
PDF
Microservices Runtimes
PDF
Containerizing legacy applications
PDF
Quixote
PPT
eZ Publish cluster unleashed revisited
Filesystems Lisbon 2018
Filesystem Abstraction with Flysystem
PyFilesystem
PHP deployment, 2016 flavor - cakefest 2016
Filesystem abstractions and msg queue sergeev - symfony camp 2018
An Enhanced Cloud Backed Frugal File System
Hybrid Cloud PHPUK2012
Scaling PHP apps
Midwest php 2013 deploying php on paas- why & how
Hopping in clouds - phpuk 17
Anatomy of a high-volume, cloud-based WordPress architecture
Develop and deploy using Hybrid Cloud Strategies confoo2012
PHP deploy 2015 flavor - talk from php tour 2015 luxembourg
File Context
OSDC 2010 | Use Distributed Filesystem as a Storage Tier by Fabrizio Manfred
Microservices and Best Practices
Microservices Runtimes
Containerizing legacy applications
Quixote
eZ Publish cluster unleashed revisited
Ad

More from Mark Niebergall (20)

PDF
Leveling Up With Unit Testing - php[tek] 2023
PDF
Leveling Up With Unit Testing - LonghornPHP 2022
PDF
Developing SOLID Code
PDF
Unit Testing from Setup to Deployment
PDF
Stacking Up Middleware
PDF
BDD API Tests with Gherkin and Behat
PDF
BDD API Tests with Gherkin and Behat
PDF
Hacking with PHP
PDF
Relational Database Design Bootcamp
PDF
Starting Out With PHP
PDF
Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)
PDF
Debugging PHP with Xdebug - PHPUK 2018
PDF
Advanced PHP Simplified - Sunshine PHP 2018
PDF
Defensive Coding Crash Course Tutorial
PDF
Inheritance: Vertical or Horizontal
PDF
Cybersecurity State of the Union
PDF
Cryptography With PHP - ZendCon 2017 Workshop
PDF
Defensive Coding Crash Course - ZendCon 2017
PDF
Leveraging Composer in Existing Projects
PDF
Defensive Coding Crash Course
Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - LonghornPHP 2022
Developing SOLID Code
Unit Testing from Setup to Deployment
Stacking Up Middleware
BDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and Behat
Hacking with PHP
Relational Database Design Bootcamp
Starting Out With PHP
Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)
Debugging PHP with Xdebug - PHPUK 2018
Advanced PHP Simplified - Sunshine PHP 2018
Defensive Coding Crash Course Tutorial
Inheritance: Vertical or Horizontal
Cybersecurity State of the Union
Cryptography With PHP - ZendCon 2017 Workshop
Defensive Coding Crash Course - ZendCon 2017
Leveraging Composer in Existing Projects
Defensive Coding Crash Course
Ad

Recently uploaded (20)

PPTX
ai tools demonstartion for schools and inter college
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
top salesforce developer skills in 2025.pdf
PPTX
L1 - Introduction to python Backend.pptx
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
Introduction to Artificial Intelligence
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
System and Network Administration Chapter 2
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
CHAPTER 2 - PM Management and IT Context
ai tools demonstartion for schools and inter college
2025 Textile ERP Trends: SAP, Odoo & Oracle
top salesforce developer skills in 2025.pdf
L1 - Introduction to python Backend.pptx
Softaken Excel to vCard Converter Software.pdf
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Which alternative to Crystal Reports is best for small or large businesses.pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Introduction to Artificial Intelligence
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
System and Network Administration Chapter 2
Upgrade and Innovation Strategies for SAP ERP Customers
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
ManageIQ - Sprint 268 Review - Slide Deck
How to Choose the Right IT Partner for Your Business in Malaysia
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
CHAPTER 2 - PM Management and IT Context

Filesystem Management with Flysystem at PHP UK 2023