Filesystem

Because users can choose their storage backend, the filesystem should be accessed by using the appropriate filesystem classes.

Filesystem classes can be injected automatically with dependency injection. This is the user filesystem. For a simplified filestystem for app specific data see IAppData

Writing to a file

All methods return a Folder object on which files and folders can be accessed, or filesystem operations can be performed relatively to their root. For instance for writing to file:nextcloud/data/myfile.txt you should get the root folder and use:

  1. <?php
  2. namespace OCA\MyApp\Storage;
  3. use OCP\Files\IRootFolder;
  4. class AuthorStorage {
  5. /** @var IRootStorage */
  6. private $storage;
  7. public function __construct(IRootFolder $storage){
  8. $this->storage = $storage;
  9. }
  10. public function writeTxt($content) {
  11. $userFolder = $this->storage->getUserFolder('myUser');
  12. // check if file exists and write to it if possible
  13. try {
  14. try {
  15. $file = $userFolder->get('myfile.txt');
  16. } catch(\OCP\Files\NotFoundException $e) {
  17. $userFolder->touch('myfile.txt');
  18. $file = $userFolder->get('myfile.txt');
  19. }
  20. // the id can be accessed by $file->getId();
  21. $file->putContent($content);
  22. } catch(\OCP\Files\NotPermittedException $e) {
  23. // you have to create this exception by yourself ;)
  24. throw new StorageException('Cant write to file');
  25. }
  26. }
  27. }

Reading from a file

Files and folders can also be accessed by id, by calling the getById method on the folder.

  1. <?php
  2. namespace OCA\MyApp\Storage;
  3. use OCP\Files\IRootFolder;
  4. class AuthorStorage {
  5. /** @var IRootFolder */
  6. private $storage;
  7. public function __construct(IRootFolder $storage){
  8. $this->storage = $storage;
  9. }
  10. public function getContent($id) {
  11. $userFolder = $this->storage->getUserFolder('myUser');
  12. // check if file exists and read from it if possible
  13. try {
  14. $file = $userFolder->getById($id);
  15. if($file instanceof \OCP\Files\File) {
  16. return $file->getContent();
  17. } else {
  18. throw new StorageException('Can not read from folder');
  19. }
  20. } catch(\OCP\Files\NotFoundException $e) {
  21. throw new StorageException('File does not exist');
  22. }
  23. }
  24. }