Zend Cache Backend Static Remove/Clean - php

I'm trying to implement a cache using Zend Cache. I use the following code to initialize the caches.
$tagCache = Zend_Cache::factory('Core',
'File',
array('automatic_serialization' => true),
array('cache_dir' => $cfg['instdir']. 'Cache_dir'));
$cache = Zend_Cache::factory('Capture',
'Static',
array(),
array('index_filename' => 'index',
'public_dir' => $cfg['instdir'] . 'Cached',
'tag_cache' => $tagCache));
I use the following code to start caching:
$id = bin2hex($_SERVER["REQUEST_URI"]);
$cache->start($id, array());
The cache files are generated but I can't delete them using the remove() method (the cache doesn't refresh):
$cache->remove($id); // id generated like above from the REQUEST_URI of the page I want to refresh
What am I doing wrong ?
Thanks.

$cache->remove() is a proxy to the backend's remove() method. In this case you are using the Static backend and so we look in there to find out what's happening.
My reading of that method leads me to believe that the $id parameter to remove has to be a filename, so:
$cache->remove('index');
will work.
The more usual way to clear a cache is to use the clean() method though. See the manual.

Related

How do I change the timeout for PHP ApaiIO Amazon library?

How do I change the timeout for the Amazon product library PHP client? I searched the code for timeout, but it's not obvious how to pass a different timeout value.
https://github.com/Exeu/apai-io/search?utf8=%E2%9C%93&q=timeout
Based on the link you provided, there is no way to pass in a parameter for the timeout. You can see it's hardcoded right there in the constructor. However you can easily extend the class and re-write the constructor like this. Just call eRequest instead of Request.
You can see that $options is private, so you know it's not being edited elsewhere and a simple ctrl-f can tell you that it's not being changed anywhere else in that class, so these are your only options for changing it.
class eRequest extends Request{
__construct(array $options = array(), $timeout=10){
$this->options = array(
self::USERAGENT => "ApaiIO [" . ApaiIO::VERSION . "]",
self::CONNECTION_TIMEOUT => $timeout,
self::TIMEOUT => $timeout,
self::FOLLOW_LOCATION => 1
);
$this->setOptions($options);
}
}
..Or if there are other parts of the library that use this, you will have to alter the actual source of the library.

Zend Framework 2 Cache filesystem

I've been using the filesystem adapter for cacheing data.
E.g..
$cache = StorageFactory::factory(array(
'adapter' => array(
'name' => 'filesystem'
'options' => array('ttl' => 1800, 'cache_dir' => './data/cache'),
),
));
But when using the getItem() function AFTER the TTL clocks over it returns false on success etc, which it should... However, I've noticed that the file remains on the system. Is there a way of forcing the use of the cached file?
Scenario being.. My cache is outdated, when it runs some expensive functions they return nothing or it times out.. So I'd like to use the cache instead!
Just wondering if thats possible?
Thanks!
Here is a useful link to the official ZF2 documentation for the specific StorageAdapter that you are using (filesystem).

Expiration time makes error in caching

I'm using file caching (CFileCache) to show a simple message from a database table.
When page load for the first time it works correct but when I reload page it makes an Error as:
include(CTimestampBehavior.php) [function.include]: failed to open stream: No such file or directory
And This error remains until TIME EXPIRATION which I set in cache->set() and next page load just one time and it makes error again and so on.
Here is my method to handle caching:
public static function getLatest()
{
//see if it is in the cache, if so, just return it
if( ($cache=Yii::app()->cache)!==null)
{
$key='TrackStar.ProjectListing.SystemMessage';
if(($sysMessage=$cache->get($key))!==false)
return $sysMessage;
}
//The system message was either not found in the cache, or
//there is no cache component defined for the application
//retrieve the system message from the database
$sysMessage = SysMessage::model()->find(array(
'order'=>'t.update_time DESC',
));
if($sysMessage != null)
{
//a valid message was found. Store it in cache for future retrievals
if(isset($key))
//$cache->set($key,$sysMessage,300);
$cache->set($key, $sysMessage, 300, new CDbCacheDependency('SELECT MAX(update_time) FROM tbl_sys_message'));
return $sysMessage;
}
else
return null;
}
Error occures in this line:
if(($sysMessage=$cache->get($key))!==false)
I'm new to Yii and caching and have no idea about it.
UPDATE:
behaviors method of AR models:
public function behaviors()
{
return array(
'CTimestampBehavior' => array(
'class' => 'zii.behaviors.CTimestampBehavior',
'createAttribute' => 'create_time',
'updateAttribute' => 'update_time',
'setUpdateOnCreate' => true,
),
);
}
This looks like your issue is either that:
framework/zii/behaviors/CTimestampBehavior.php is missing
framework/zii/behaviors/CTimestampBehavior.php doesn't have correct permissions to be read by your server user
You are using opcode cache (APC?) and there are some issues on that end, (though reports for this seem to be for random occurrences). Try disabling it.
For some unknown reason Yii doesn't import your zii routes
In any event I suggest trying a workaround of adding "zii.behaviors.CTimestampBehavior" to your main.php configuration file "import" section. Or simply calling Yii::import('zii.behaviors.CTimestampBehavior'); in your function. Hopefully that works and you can continue with your work while diving deaper into the issue when you've got the time.
If it doesn't you can investigate the above (and at least people who come here will have more information to work with)

Zend Framework 2 Json, default routing

I am building up a user creation page (controller/module: User) which has UI controls (DOJO filterselectbox, username, etc.). The UI controls get populated with a Json service deployed as module (module name/controller) myService, and action populatelist().
populatelist returns data as Json to client and the client dojo ui elements use that as a memory store.
I have 2 modules, User and myService. For the User module, I have setup default page as register and in register.phtml as given below. I have added logic for user input validation and data post.
module.config.php of module: User
'defaults' => array(
'controller' => 'User\Controller\User',
'action' => 'register',
),
Json is registered in module myService. register.phtml makes a call like:
myservice = new dojo.rpc.JsonService("myService/populatelist");
var dojoDeferredObject=myservice.getCategoryList();
//comment: getCtegoryList is actual method of remote object which returns the json data
When I open the url as http://localhost/user, any reference to myService JSONRPC call works perfectly fine: it parses the JSON call as http://localhost/myService/populatelist and I get the data I need.
When I access the url as http://localhost/user/register, things fail with 404 page not found exception for every Json RPC call. Reason is, the RPC call is going on a non-existent path, i.e. http://localhost/user/myService/populatelist instead of http://localhost/myService/populatelist.
Somewhere I have missed a configuration which is resulting in this issue. I do not want to hardcode path of Json service Module myService.
I believe the problem is this line:
$server->setTarget('myService/populatelist');
in the below code, used to set up the Json Service. This is adding up to the path which does not exist. But I am not sure how can I control it as I want a separate module for Json service.
$class = "MOCAPI\Model\MOCGuest";
$server = new Server();
$server->setClass($class);
//echo $_SERVER['REQUEST_METHOD'];
if ('GET' == $_SERVER['REQUEST_METHOD']) {
$server->setTarget('myService/populatelist')
->setEnvelope(Smd::ENV_JSONRPC_2);
$smd = $server->getServiceMap();
// Set Dojo compatibility:
$smd->setDojoCompatible(true);
header('Content-Type: application/json');
echo $smd;
return $this->getResponse();
} else {
//$server->handle();
}
You should use routes and url() helper to build urls and relative and absolutes paths, instead of raw 'myService/populatelist'.
Check the docs at https://framework.zend.com/manual/2.4/en/modules/zend.view.helpers.url.html (version 2.4, but it almost the same in zf2.* and zf3).

How to Bootstrap Sessions in Zend Framework 2

What is the best way to go about getting sessions up and running in Zend Framework 2? I've tried setting session_start() in my index.php file but then that gets run before any autoloaders have been bootstrapped, leading to incomplete objects sitting in my sessions.
In ZF1 you could have it initialize sessions by adding some options into the config, but I'm at a loss on how to do this in ZF2.
If i understand you correctly, all you wanna do is have your session working properly in your modules? Assuming that's correct there are two single steps.
1) Create the config: module.config.php
return array(
'session' => array(
'remember_me_seconds' => 2419200,
'use_cookies' => true,
'cookie_httponly' => true,
),
);
2) Start your Session: Module.php
use Zend\Session\Config\SessionConfig;
use Zend\Session\SessionManager;
use Zend\Session\Container;
use Zend\EventManager\EventInterface;
public function onBootstrap(EventInterface $evm)
{
$config = $evm->getApplication()
->getServiceManager()
->get('Configuration');
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config['session']);
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->start();
/**
* Optional: If you later want to use namespaces, you can already store the
* Manager in the shared (static) Container (=namespace) field
*/
Container::setDefaultManager($sessionManager);
}
Find more options in the documentation of \Zend\Session\Config\SessionConfig
If you want to store cookies too, then please see this Question. Credits to Andreas Linden for his initial answer - I'm simply copy pasting his.

Categories