ZF2 - Saving a result of a function in cache - caching

I made a view helper that checks if an external URL exists before outputting it. Some of those URLs are in my main layout, so that check is quite slowing down my site by calling all those urls all the times, to check if they exist. I would like to save the output of that function so that it only checks an URL if the same one hasn't been checked already in less than an hour, or a day. I believe I should use Zend Cache to do that? But I have no idea where to start, do you have any suggestions, easy solutions or some basic tutorial to learn? Thanks!

Add global config for cache service, like here:
config/autoload/global.php
'service_manager' => array(
'abstract_factories' => array(
'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
)
),
config/autoload/cache.global.php
return array(
'caches' => array(
// Cache config
)
)
Use factory to create your View Helper:
Application/Module.php::getViewHelperConfig()
'LinkHelper' => function ($sm) {
$locator = $sm->getServiceLocator();
return new LinkHelper($locator->get('memcached'))
}
Use cache service in your View Helper:
LinkHelper.php
protected $cache;
public function __construct($cache)
{
$this->cache = $cache;
}
public function __invoke($url)
{
$cacheKey = md5($url);
if ($this->cache->hasItem($cacheKey) {
return $this->cache->getItem($cacheKey);
}
$link = ''; // Parse link
$this->cache->setItem($cacheKey, $link);
return $link;
}

Related

Laravel: Cache with pagination clear issue

I have laravel (7.x) application. I recently added the cache functionality for the performance boost. After implementing the cache functionality, I was having trouble with the pagination while loading the data in grid format, so I googled for the solution and found this Pagination with cache in Laravel.
Although, it did solve my problem. But, the case is that I have about 100 pages and due to the solution I found, each page has it's own cache. Now, if I create or update any record then it doesn't reflect in the grid because the data is loaded from the cache.
PostController.php:
...
$arraySearch = request()->all();
# calculating selected tab
$cache = (!empty(request()->inactive)) ? 'inactive' : 'active';
$cacheKey = strtoupper("{$this->controller}-index-{$cache}-{$arraySearch['page']}");
# caching the fetch data
$arrayModels = cache()->remember($cacheKey, 1440, function() use ($arraySearch) {
# models
$Post = new Post();
# returning
return [
'active' => $Post->_index(1, 'active', $arraySearch),
'inactive' => $Post->_index(0, 'inactive', $arraySearch),
];
});
...
Post.php:
public function _index($status = 1, $page = null, $arraySearch = null)
{
...
$Self = self::where('status', $status)
->orderBy('status', 'ASC')
->orderBy('title', 'ASC')
->paginate(10);
...
return $Self;
}
How do I clear all this cache to show the newly created or updated record to with the updated values.?
1. Store All pages under the same tag:
As seen on the documentation: https://laravel.com/docs/master/cache#storing-tagged-cache-items
You can use tags to group cached items.
$cacheTag = strtoupper("{$this->controller}-index-{$cache}");
$arrayModels = cache()->tags([$cacheTag])->remember($cacheKey, 1440, function() use ($arraySearch) {
...
2. Set an event listener on Post to clear the tag
You can run an Event listener on your Post update() or create() events.
https://laravel.com/docs/7.x/eloquent#events-using-closures
You can then clear the tag cache using
Cache::tags([$cacheTag])->flush();
I know this isn't the proper solution. But, until I find the proper way to do it, this is the option I am kind of stuck with.
PostController.php:
public function index()
{
...
$arraySearch = request()->all();
# calculating selected tab
$cache = (!empty(request()->inactive)) ? 'inactive' : 'active';
$cacheKey = strtoupper("{$this->controller}-index-{$cache}-{$arraySearch['page']}");
# caching the fetch data
$arrayModels = cache()->remember($cacheKey, 1440, function() use ($arraySearch) {
# models
$Post = new Post();
# returning
return [
'active' => $Post->_index(1, 'active', $arraySearch),
'inactive' => $Post->_index(0, 'inactive', $arraySearch),
];
});
...
}
public function store()
{
...
Artisan::call('cache:clear');
...
}
I'll post the proper solution when I find one. Till then I am using this one.
There is a method in Laravel Model class called booted (not boot, which is having a different purpose). This method runs every time something is "saved" (including "updated") or "deleted".
I have used this as following (in a Model; or a Trait, included in a Model):
protected static function booted(): void
{
$item = resolve(self::class);
static::saved(function () use ($item) {
$item->updateCaches();
});
static::deleted(function () use ($item) {
$item->updateCaches();
});
}
"updateCaches" is a method in the Trait (or in the Model), that can have the code to update the cache.

ZF2 get global session container

I found how to get a session container like this:
$session = new \Zend\Session\Container('base');
But what if I need to access the session in many places during processing a HTTP request.
Let's say in the Application module's indexAction in the IndexController, then I redirect it to the User\Controller\IndexController and need to access the session again, and then in a view helper or two, and who knows how often more.
When constructing the session container every time anew, that is a waste of processing time. Yes, I debugged it to see what's going on in the constructor, and yes, there is some code executed behind the scenes. It is not as if the constructor would just return a global variable or something else which would be immutable and doesn't need a construction process.
So what to do?
Should I create a service for it?
a controller plugin?
a view helper?
a service and a controller plugin and a view helper, with the latter calling the service?
I'm sure it is something that many people must have come across and have dealt with, but I can't find any information on this.
Any hint is dearly appreciated.
Many thanks in advance! :-)
Here's a more refined and improved version.
It consists of the service "SessionService", a ViewHelper (which calls the SessionService), a ControllerPlugin (which also calls the SessionService), and shows how to set them up in the configuration file "module.config.php".
Make sure you set "use" paths or use absolute class paths in config.
SessionService.php:
class SessionService
{
protected $sessionContainer;
public function setSessionContainer(
$sessionContainer
) {
$this->sessionContainer = $sessionContainer;
}
public function __invoke() {
return $this->sessionContainer;
}
}
SessionHelper.php:
class SessionHelper extends \Zend\View\Helper\AbstractHelper
{
protected $sessionService;
public function setSessionService(
$sessionService
) {
$this->sessionService = $sessionService;
}
public function __invoke() {
return $this->sessionService;
}
}
SessionPlugin.php:
class SessionPlugin extends AbstractPlugin
{
protected $sessionService;
public function setSessionService(
$sessionService
) {
$this->sessionService = $sessionService;
}
public function __invoke() {
return $this->sessionService;
}
}
module.config.php:
'service_manager' => array(
'factories' => array(
'sessionService' => function(
ServiceLocatorInterface $serviceLocator
) {
$sessionContainer = new \Zend\Session\Container('base');
$sessionService = new SessionService();
$sessionService->setSessionContainer($sessionContainer);
return $sessionService;
},
),
),
'controller_plugins' => array(
'factories' => array(
'sessionPlugin' => function(
AbstractPluginManager $pluginManager
) {
$sessionService = $pluginManager->getServiceLocator()->get('sessionService');
$sessionPlugin = new SessionPlugin();
$sessionPlugin->setSessionService($sessionService);
return $sessionPlugin;
},
),
),
'view_helpers' => array(
'factories' => array(
'sessionHelper' => function (
AbstractPluginManager $helperPluginManager
) {
$sessionService = $helperPluginManager->getServiceLocator()->get('sessionService');
$sessionHelper = new SessionHelper();
$sessionHelper->setSessionService($sessionService);
return $sessionHelper;
},
),
),
In your Controller write:-
use Zend\Session\Container;
Make Session variable
$user_session = new Container('user');
'user' is Your Session Name To put Value in Your Session write:
$user_session->username = 'xyz';
After Storing You can Access Your Session By:
$user_session-> username
To destroy Session Variable Use:
$session = new Container('user');
$session->getManager()->getStorage()->clear('user');
it is Just Like : -
unset($_SESSION['user']);
http://wownewcode.blogspot.in/2013/12/set-session-in-zend-framework-2.html
Once you've initialized a session Container you can just re-use it with $_SESSION['container_name'];
Basically $session = new \Zend\Session\Container('base'); will create an ArrayObject named base inside $_SESSION. One advantage of initializing by creating a Container is that you can specify a TTL or expiration after x-hops.
$_SESSION['base']['key'] = "store this value";
I think you need to use session Manager and service with the container storage to achieve your goal.
you can set it in your application Module
Application\Module.php
use Zend\Session\Config\SessionConfig;
public function onBootstrap(EventInterface $e)
{
//Your other code here
//configure session
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config['session']);
}
and in module.config.php
'session' => array(
'save_path' => realpath(ZF2PROJECT_ROOT . '/data/session'),
'name' => 'ZF2PROJECT_SESSION',
),
and in your services you can use like this. Forexample in Authentication service.
class AuthenticationService
{
protected $storage = null;
public function getStorage()
{
if (null === $this->storage) {
$this->setStorage(new Storage\Session());
}
return $this->storage;
}
}
Here is my current provisional solution or workaround, consisting of:
- a service for storing the session container object.
- a controller plugin for easy access to the session container, without having to inject a dependency for it in every controller.
The session service:
class Session
{
private static $container;
public function getContainer() {
if (!isset(self::$container)) {
self::$container = new \Zend\Session\Container('base');
}
return self::$container;
}
public function __invoke() {
return $this->getContainer();
}
}
The controller plugin:
class Session extends AbstractPlugin
{
protected $sessionService;
public function __construct(
SessionService $sessionService
) {
$this->sessionService = $sessionService;
}
public function getContainer() {
return $this->sessionService->getContainer();
}
public function __invoke() {
return $this->getContainer();
}
}
Configuration in module.config.php:
'service_manager' => array(
'factories' => array(
'sessionService' => function($sm) {
return new Application\Service\Session\Session();
},
),
),
'controller_plugins' => array(
'factories' => array(
'session' => function($serviceLocator) {
$sessionService = $serviceLocator->get('sessionService');
return new Application\Service\Mvc\Controller\Plugin\Session($sessionService);
},
),
),
Usage example in any controller or controller plugin method:
$sessionContainer = $this->session->getContainer();
or short form (because session service and controller plugin both implement __invoke):
$sessionContainer = $this->session();
and then can use the session container to store any variables in it, like this:
$sessionContainer->foo = 'bar';
Because the session service is created by a factory function through module.config.php, it is only created once.
The actual session container is a static variable in the session service and only created once, i.e. if it doesn't exist.
In subsequent calls to the getSessionContainer function, this only once created static session container is returned.
This is just a provisional workaround solution, works for me for now, but for making it re-usable for other applications also, it should provide functions to customize the session container name and the storage place and strategy, those parts are missing in this simple workaround solution.
Note: A view helper should not be necessary for it. Session variables should not be set in a view, and if a view needs read access to them, the data should be passed via a view model from controller to view.

Laravel 4 : Route to localhost/controller/action

I'm more or less new to Laravel 4. I've never used routes before but normally what I'm used to is url/controller/action and then the backend routing for me. I've read the documentation for routes and controllers a few times as well as read through some tutorials and so, I'm trying to figure out how to get this to work without writing a route for every controller and action.
I tried something like
Route::get('{controller}/{action}', function($controller, $action = 'index'){
return $controller."#".$action;
});
Now then, I know this is wrong since it doesn't work, but what am I missing? On most tutorials and stuff I'm seeing an route for more or less every controller and action like:
Route::get('/controller/action' , 'ControllerName#Action');
Which seems silly and like a waste of time to me.
Is there anyway to achieve what I want?
If you are looking for a more automated routing, this would be the Laravel 4 way:
Route:
Route::controller('users', 'UsersController');
Controller (in this case UsersController.php):
public function getIndex()
{
// routed from GET request to /users
}
public function getProfile()
{
// routed from GET request to /users/profile
}
public function postProfile()
{
// routed from POST request to /users/profile
}
public function getPosts($id)
{
// routed from GET request to: /users/posts/42
}
As The Shift Exchange mentioned, there are some benefits to doing it the verbose way. In addition to the excellent article he linked, you can create a name for each route, for example:
Route::get("users", array(
"as"=>"dashboard",
"uses"=>"UsersController#getIndex"
));
Then when creating urls in your application, use a helper to generate a link to a named route:
$url = URL::route('dashboard');
Links are then future proofed from changes to controllers/actions.
You can also generate links directly to actions which would still work with automatic routing.
$url = URL::action('UsersController#getIndex');
app\
controllers\
Admin\
AdminController.php
IndexController.php
Route::get('/admin/{controller?}/{action?}', function($controller='Index', $action='index'){
$controller = ucfirst($controller);
$action = $action . 'Action';
return App::make("Admin\\{$controller}Controller")->$action();
});
Route::get('/{controller?}/{action?}', function($controller='Index', $action='index'){
$controller = ucfirst($controller);
$action = $action . 'Action';
return App::make("{$controller}Controller")->$action();
});
I come from .Net world and routing is typically done:
/{Controller}/{action}/{id}
Which looks like:
/Products/Show/1 OR /Products/Show/Beverages
In Laravel I accomplish this routing like so:
Route::get('/{controller?}/{action?}/{id?}', function ($controller='Home', $action='index', $id = null) {
$controller = ucfirst($controller);
return APP::make("{$controller}Controller")->$action($id);
});
The controller would look roughly like so:
class ProductsController extends BaseController {
public function Show($id) {
$products = array( 1 => array("Price" => "$600","Item" => "iPhone 6"),
2 => array("Price" => "$700", "Item" => "iPhone 6 Plus") );
if ($id == null) {
echo $products[1]["Item"];
} else {
echo $products[$id]["Item"];
}
}
}

How to approach caching in ZF2

I am just starting to get my head into caching as a whole. I have a simple indexAction() that fetches all given Datasets. My approach is:
check for existing key 'controllername-index-index'
if existing: return the value of the key
if not existing, do the normal action and add the key
The value inside the key should be the ViewModel that will be generated and populated with my data.
Here's what i have done so far:
<?php
public function indexAction()
{
$sl = $this->getServiceLocator();
// $cache = $sl->get('cache');
// $key = 'kennzahlen-index-index';
//
// if ($cache->hasItem($key)) {
// return $cache->getItem($key);
// }
$viewModel = new ViewModel();
$viewModel->setTemplate('kennzahlen/index/index');
$entityService = $sl->get('kennzahlen_referenzwert_service');
$viewModel->setVariable('entities', $entityService->findAll());
// $cache->setItem($key, $viewModel);
return $viewModel;
}
The Caching parts are commented out for testing purposes, but basically this is all that i am doing. The Caching config/service looks like the following:
<?php
'cache' => function () {
return \Zend\Cache\StorageFactory::factory(array(
'adapter' => array(
'name' => 'filesystem',
'options' => array(
'cache_dir' => __DIR__ . '/../../data/cache',
'ttl' => 100
),
),
'plugins' => array(
array(
'name' => 'serializer',
'options' => array(
)
)
)
));
},
The serialization and caching works quite well, but i am surprised by the missing results. Going by what the ZendDevelopersToolbar tells me, the times WITHOUT caching range between 1.8s to 2.5s. Having the caching parts uncommented (enabled) doesn't really improve the loading time of my page at all.
So my question is: Is this approach completely wrong? Are there different, more speedy parts, that can be saved with some neat configuration tricks?
I Feel that a 2 second load time of a page is DEFINITELY too slow. 1s to me is the maximum given a huge amount of data, but certainly not anything more than that :S
All help/hints/suggestions will be greatly appreciated. Thanks in advance!
One option would be to cache the complete output of your page, for example based on the route match. You need to listen between routing and dispatching which route has been found as match and then act accordingly:
namespace MyModule;
use Zend\Mvc\MvcEvent;
class Module
{
public function onBootstrap(MvcEvent $e)
{
// A list of routes to be cached
$routes = array('foo/bar', 'foo/baz');
$app = $e->getApplication();
$em = $app->getEventManager();
$sm = $app->getServiceManager();
$em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($sm) {
$route = $e->getRouteMatch()->getMatchedRouteName();
$cache = $sm->get('cache-service');
$key = 'route-cache-' . $route;
if ($cache->hasItem($key)) {
// Handle response
$content = $cache->getItem($key);
$response = $e->getResponse();
$response->setContent($content);
return $response;
}
}, -1000); // Low, then routing has happened
$em->attach(MvcEvent::EVENT_RENDER, function($e) use ($sm, $routes) {
$route = $e->getRouteMatch()->getMatchedRouteName();
if (!in_array($route, $routes)) {
return;
}
$response = $e->getResponse();
$content = $response->getContent();
$cache = $sm->get('cache-service');
$key = 'route-cache-' . $route;
$cache->setItem($key, $content);
}, -1000); // Late, then rendering has happened
}
}
The second listener checks at the render event. If that happens, the result of the response will be cached.
This system (perhaps not with 100% copy/paste, but the concept) works because if you return a Response during the route or dispatch event, the application will short circuit the application flow and stop further triggering listeners. It will then serve this response as it is.
Bear in mind it will be the complete page (including layout). If you don't want that (only the controller), move the logic to the controller. The first event (now route) will be dispatch of the controller. Listen to that early, so the normal execution of the action will be omitted. To cache the result, check the render event for the view layer to listen to.
/update: I wrote a small module to use this DRY in your app: SlmCache

load multiple models in array - codeigniter framework

<?php
class Home extends CI_Controller
{
public function __construct()
{
// load libraries //
$this->load->library('session');
$this->load->library('database');
$this->load->library('captcha');
// alternative
$this->load->library(array('session', 'database', 'captcha'));
// load models //
$this->load->model('menu_model', 'mmodel');
$this->load->model('user_model', 'umodel');
$this->load->model('admin_model', 'amodel');
// alternative
$this->load->model(array(?));
}
}
?>
How can i load all models in array? is it possible?
For models, you can do this:
$models = array(
'menu_model' => 'mmodel',
'user_model' => 'umodel',
'admin_model' => 'amodel',
);
foreach ($models as $file => $object_name)
{
$this->load->model($file, $object_name);
}
But as mentioned, you can create file application/core/MY_Loader.php and write your own method for loading models. I think this might work (not tested):
class MY_Loader extends CI_Loader {
function model($model, $name = '', $db_conn = FALSE)
{
if (is_array($model))
{
foreach ($model as $file => $object_name)
{
// Linear array was passed, be backwards compatible.
// CI already allows loading models as arrays, but does
// not accept the model name param, just the file name
if ( ! is_string($file))
{
$file = $object_name;
$object_name = NULL;
}
parent::model($file, $object_name);
}
return;
}
// Call the default method otherwise
parent::model($model, $name, $db_conn);
}
}
Usage with our variable from above:
$this->load->model($models);
You could also allow a separate DB connection to be passed in an array, but then you'd need to have a multidimensional array, and not the simple one we used. It's not too often you'll need to do that anyways.
I don't have any idea about the CodeIgniter 2.x but in CodeIgniter 3.x, this will also works :
$models = array(
'menu_model' => 'mmodel',
'user_model' => 'umodel',
'admin_model' => 'amodel',
);
$this->load->model($models);
Not natively, but you can easily extend Loader->model() to support that logic.
This work fine for me:
$this->load->model(array('menu_model'=>'menu','user_model'=>'user','admin_model'=>'admin'));

Resources