I am new to Drupal 8. I have found Drupal state API for cache mechanism. Can I set key expire time also with below statement?
\Drupal::state()->set('key','value');
Source : https://www.drupal.org/docs/8/api/state-api/overview
Here I am able to set key but I want to clear it after 60 minutes.
Is there any other cache mechanism I can use?
Any suggestion would be helpful.
Thanks in advance.
Instead of using State directly, you can use your own wrapper that uses the KeyValueExpirableFactoryInterface. See the Drupal docs for more about the KeyValueStore API.
Example:
$kvStorage = \Drupal::service('keyvalue.expirable')->get('my_collection_name');
$kvStorage->setWithExpire('my_key', 'my_value', time() + 3600);
Also, this article from Palantir has a good overview of the various data-storage APIs in Drupal 8 and what they are best for.
The other answer is incorrect. You specify the length of time in seconds from the current request. If you call time(), you're telling Drupal to store the value for a very, very, very long time.
// Get the key value collection
$kv_store = \Drupal::service('keyvalue.expirable')->get('my_module_name');
// Get the value or null
$token = $kv_store->get('token', null);
// If no value, set the value
if (!$token) {
$kv_storage->setWithExpire('token', 'my_token', 3600);
}
Related
I am trying to develop a webapp using Google Apps Script to be embedded into a Google Site which simply displays the contents of a Google Sheet and filters it using some simple parameters. For the time being, at least. I may add more features later.
I got a functional app, but found that filtering could often take a while as the client sometimes had to wait up to 5 seconds for a response from the server. I decided that this was most likely due to the fact that I was loading the spreadsheet by ID using the SpreadsheetApp class every time it was called.
I decided to cache the spreadsheet values in my doGet function using the CacheService and retrieve the data from the cache each time instead.
However, for some reason this has meant that what was a 2-dimensional array is now treated as a 1-dimensional array. And, so, when displaying the data in an HTML table, I end up with a single column, with each cell being occupied by a single character.
This is how I have implemented the caching; as far as I can tell from the API reference I am not doing anything wrong:
function doGet() {
CacheService.getScriptCache().put('data', SpreadsheetApp
.openById('####')
.getActiveSheet()
.getDataRange()
.getValues());
return HtmlService
.createTemplateFromFile('index')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getData() {
return CacheService.getScriptCache().get('data');
}
This is my first time developing a proper application using GAS (I have used it in Sheets before). Is there something very obvious I am missing? I didn't see any type restrictions on the CacheService reference page...
CacheService stores Strings, so objects such as your two-dimensional array will be coerced to Strings, which may not meet your needs.
Use the JSON utility to take control of the results.
myCache.put( 'tag', JSON.stringify( myObj ) );
...
var cachedObj = JSON.parse( myCache.get( 'tag' ) );
Cache expires. The put method, without an expirationInSeconds parameter expires in 10 minutes. If you need your data to stay alive for more than 10 minutes, you need to specify an expirationInSeconds, and the maximum is 6 hours. So, if you specifically do NOT need the data to expire, Cache might not be the best use.
You can use Cache for something like controlling how long a user can be logged in.
You could also try using a global variable, which some people would tell you to never use. To declare a global variable, define the variable outside of any function.
I need a way to store temporary data for anonymous users.
Apparently this is not possible with:
\Drupal::service('user.private_tempstore')
Unless you write a custom constructor for the session management and stuff, which seems a little far-fetched to me?
I tried using
\Drupal::service('user.shared_tempstore')
But that saves the temp data for all anonymous users. So it's not linked to a single user.
Using raw $_SESSION['data'] works fine, but I'm not sure if I'm supposed to be doing this in Drupal and how safe/unsafe it is to do this?
Sessions (Drupal 8) are used via the simple Session implementation of SessionInterface interface. See Complete Tutorial of Sessions (Drupal 8).
Example:
use Symfony\Component\HttpFoundation\Session\Session;
$session = new Session();
$session->start();
// set and get session attributes
$session->set('name', 'Yash');
$session->get('name');
// set flash messages
$session->getFlashBag()->add('notice', 'Profile updated');
// retrieve messages
foreach ($session->getFlashBag()->get('notice', array()) as $message) {
echo '<div class="flash-notice">'.$message.'</div>';
}
I am not answering your specific question (regarding $_SESSION) because I have successfully used:
$session = \Drupal::service('user.private_tempstore')->get('your_module');
$session->set('whatever', $whatever);
from within procedural code (i.e. hooks, themes) without problems.
Pay attention that this private tempstore has to be assigned to a module (for the lack of a better way of saying this) which is the purpose of this line
$session = \Drupal::service('user.private_tempstore')->get('your_module')
After you get the private tempostore you can now set and get the session values:
$session->get('whatever');
$session->set('whatever', $whatever);
EDIT
Sorry, you explained correctly. I didn't get the critical part 100% ;)
You can always access the Session object from the request.
$session = \Drupal::request()->getSession();
$session->set('whatever', 'hello');
$value = $session->get('whatever', 'default');
I've been using plain PHP $_SESSION variables for a while now.
Did some research on them and they should be perfectly safe to use.
They're working correctly everywhere I use them and they have been working correctly for a while.
Don't think there's any issue using them in Drupal 8.
I am trying to develop a webapp using Google Apps Script to be embedded into a Google Site which simply displays the contents of a Google Sheet and filters it using some simple parameters. For the time being, at least. I may add more features later.
I got a functional app, but found that filtering could often take a while as the client sometimes had to wait up to 5 seconds for a response from the server. I decided that this was most likely due to the fact that I was loading the spreadsheet by ID using the SpreadsheetApp class every time it was called.
I decided to cache the spreadsheet values in my doGet function using the CacheService and retrieve the data from the cache each time instead.
However, for some reason this has meant that what was a 2-dimensional array is now treated as a 1-dimensional array. And, so, when displaying the data in an HTML table, I end up with a single column, with each cell being occupied by a single character.
This is how I have implemented the caching; as far as I can tell from the API reference I am not doing anything wrong:
function doGet() {
CacheService.getScriptCache().put('data', SpreadsheetApp
.openById('####')
.getActiveSheet()
.getDataRange()
.getValues());
return HtmlService
.createTemplateFromFile('index')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getData() {
return CacheService.getScriptCache().get('data');
}
This is my first time developing a proper application using GAS (I have used it in Sheets before). Is there something very obvious I am missing? I didn't see any type restrictions on the CacheService reference page...
CacheService stores Strings, so objects such as your two-dimensional array will be coerced to Strings, which may not meet your needs.
Use the JSON utility to take control of the results.
myCache.put( 'tag', JSON.stringify( myObj ) );
...
var cachedObj = JSON.parse( myCache.get( 'tag' ) );
Cache expires. The put method, without an expirationInSeconds parameter expires in 10 minutes. If you need your data to stay alive for more than 10 minutes, you need to specify an expirationInSeconds, and the maximum is 6 hours. So, if you specifically do NOT need the data to expire, Cache might not be the best use.
You can use Cache for something like controlling how long a user can be logged in.
You could also try using a global variable, which some people would tell you to never use. To declare a global variable, define the variable outside of any function.
I don't know much about joomla. I found this:
JFactory::getSession();
Here I found that there is an expire date, but I can't make it work.
http://www.techportal.co.za/joomla/joomla-tutorials/304
Could you give an working example?
Just want when a user reopen the browser the data stored in the last session to be available. Also have to say that I'm using an outside domain to login, so in this case I don't care about internal ways of joomla handling users.
The 4 sections you can see in the documentation you're using there need to be passed through in an array (called $options in the API)
So you'd need to pass
$time=99; //time in minutes
$options = array(
"expire" => $time,
);
$session =& JFactory::getSession($options);
Note by default this is handled by a param in the config area of Joomla in 2.5 upwards! This might well also be the case in 1.5 - I don't have a copy of 1.5 to hand.
Ist there a way to set the maximal cache time for a USER object? (not sure if its really called object..)
The only thing i found was COA_GO - which is COA with user defined cache time - but the update to the latest revision is about two years old, which makes me hope that there is a similar core feature which made it obsolete...
/optimism off
if its not possible at all an example of how to leverage Typo3's internal cache would also solve most of my problems.
just had a look at class.t3lib_cache_manager.php, and... i don't really get it... was expecting something similar to apc...
Thanks in advance for any hint or suggestion!
Take a look at the new cObj Cache (Forge) and the blog article explaining how it works.
It basically registers a new stdWrap property which can contain a lifetime:
5 = TEXT
5 {
cache.key = mycurrenttimestamp
cache.tags = tag_a,tag_b,tag_c
cache.lifetime = 3600
data = date : U
strftime = %H:%M:%S
}