Hi there,
can anybody give an example of how to use “Grav\Common\Data”. I want to store some information, but I can’t find any example of how to use it. Can somebody help?
Regards,
Michael
Hi there,
can anybody give an example of how to use “Grav\Common\Data”. I want to store some information, but I can’t find any example of how to use it. Can somebody help?
Regards,
Michael
I don’t use Grav\Common\Data but this is a sample code I use in my plugins to store things in data folder:
$data = 'This is my data';
$filename = 'my-file.txt';
$dirname = 'my-directory';
$locator = $this->grav['locator'];
$path = $locator->findResource('user://data', true);
$dir = $path . DS . $dirname;
$fullFileName = $dir. DS . $filename;
$file = File::instance($fullFileName);
$file->save($data);
Thanks for your response. But the way you are doing it is just writing to a file, or not? . I thought there is some kind of standard way to store the data and some sort of standard format(Json) that is provided by the API.
A good way to learn how Grav works is to look at existing code, especially Grav team plugins.
I know the form plugin can store data in the user/data folder
Grav form plugin github line 4
But I am sure there are much more, and I guess you have a lot more experience with PHP than I do.
Maybe you could help me with this?: https://discourse.getgrav.org/t/get-form-data-select-input-and-add-it-to-page-frontmatter/4465/2
Of course it writes to a file in user/data folder. You can use pure PHP instead as long as it works for you.
As I know there is no standards format, it is up to you for what format is used. For example the code below stores a YAML file.
$filename = 'my-file' . YAML_EXT;
$dirname = 'my-directory';
$myArray = ['key1' => 'value1', 'key2' => 'value2'];
$data = new Data\Data($myArray);
$data->set('key3', 'value3');
$file = CompiledYamlFile::instance($this->grav['locator']->findResource("user://data/" . $dirname . "/" . $filename));
$data->file($file);
$data->save();
The content of user/data/my-directory/my-file.yaml should be:
key1: value1
key2: value2
key3: value3
You can store the files in JSON, Markdown, Yaml by using the classes in system/src/Grav/Common/File/ folder. I haven’t used these classes as I only needed to store log files and CSV files.
I do not really know that much about Grav code base other than it is very extensible. But I was also hoping for a “standard way” to write things like that. But I can see you are right, and you know what you are doing.
Could maybe you take a quick look at: https://github.com/bleutzinn/grav-plugin-add-page-by-form/blob/507be4be7ad2b94a4b403c070b99f7c03566a8b8/add-page-by-form.php#L302
From this post: https://discourse.getgrav.org/t/get-form-data-select-input-and-add-it-to-page-frontmatter/4465
I guess it is an easy fix for some one who understands the logic.
Thanks
Check out flex-directory
plugin: https://github.com/trilbymedia/grav-plugin-flex-directory
Thanks Andy, i will check it out!