Skip to content

Instantly share code, notes, and snippets.

@albertoarena
Last active November 11, 2020 12:37
Show Gist options
  • Save albertoarena/641cc352eb8bc8e17aae to your computer and use it in GitHub Desktop.
Save albertoarena/641cc352eb8bc8e17aae to your computer and use it in GitHub Desktop.
Using the Factory method pattern to have different file storage mechanisms.
<?php
/**
* Class FileStorageFactory
* A factory class that instantiates the appropriate FileStorage engine
*/
class MyProject_Service_FileStorageFactory
{
/**
* Available file storage mechanisms
* I haven't implemented them all, but this gives an idea of how it
* can be easy to add a new completely different way of storing file
* @var array
*/
protected static $mappings = array(
'local' => 'MyProject_Service_FileStorage_Local',
'webdav' => 'MyProject_Service_FileStorage_Webdav',
'sftp' => 'MyProject_Service_FileStorage_Sftp',
'gdrive' => 'MyProject_Service_FileStorage_GoogleDrive',
'dropbox' => 'MyProject_Service_FileStorage_Dropbox'
);
/**
* Cached file storage object
* @var MyProject_Service_FileStorage_Abstract
*/
protected static $cache = NULL;
/**
* Factory method
*
* @return MyProject_Service_FileStorage_Abstract
*/
public static function factory()
{
if (self::$cache === NULL)
{
// Read the file storage type from the settings
$type = MyProject_Configuration::get('filestorage');
// Create the appropriate file storage
if (array_key_exists($type, self::$mappings))
{
$className = self::$mappings[$type];
self::$cache = new $className();
}
else
{
throw new Exception('FileStorageFactory: type ' . $type . ' not found');
}
}
return self::$cache;
}
}
/**
* Abstract class FileStorage
* A static file storage that uses the correct file storage mechanism, based on configuration
*
* Sub-classes implement the methods, e.g.
* MyProject_Service_FileStorage_Local
* MyProject_Service_FileStorage_WebDav
* MyProject_Service_FileStorage_Sftp
* etc.
*/
abstract class MyProject_Service_FileStorage_Abstract
{
/**
* Save a file
* @param string $filename file name on the local file system
* @return bool|int ID of the filename saved, or FALSE if it failed
*/
abstract public function put($filename)
{
//
}
/**
* Get a file
* @param int $id ID of the filename
* @return bool|array Filename info, or FALSE if it failed
*/
abstract public function get($id)
{
//
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment