ukyo

AvbFastCache Module

Recommended Posts

AvbFastCache Module

Module AuthorBig Thanks to phpFastCache authorsUsage Almost Like original phpfastcache library :

I made some modification on original phpfastcache library for use it with ProcessWire. On my side i tested files and sqlite its look working well.

You can set default settings from module setting panel or you can use it like original library with custom settings for each call, from module setting panel you can set storage type, cache path, security key, fallback and also you can delete cached data from module settings panel.

Modified set function, working like core $cache->get function this function will check a cached data exist ? if not save cache data and return cached data back.

Here is some example usages :

// Load Module
$AvbFastCache = $modules->AvbFastCache;
// Set cache settings from module
$_c = phpFastCache($AvbFastCache->storage, $AvbFastCache->getConfig(), $AvbFastCache->expire);

$output = $_c->set("cacheKeyword", function($page)) {
    $output = '<h1>{$page->title}</h1>';
    $output .= "<div class='body'>{$page->body}</div>";
    
    return $output;
});

//=> OR

// Do MemCache
$_c2 = phpFastCache("memcached");

// Write to Cache Save API Calls and Return Cache Data
echo $_c2->set("identity_keyword", function()) {
    $results = cURL->get("http://www.youtube.com/api/json/url/keyword/page");

    $output = "";
    foreach($results as $video) {
        $output .= $vieo->title; // Output Your Contents HERE
    }

    return $output;
}, 3600*24);

// This will check id=1 or parent_id=1 and will return last modified page UNIX_TIMESTAMP as result
echo $AvbFastCache->getLastModified(1);

// This will check id=1 or parent_id=1 and template=basic-page and will return last modified page UNIX_TIMESTAMP as result
echo $AvbFastCache->getLastModified(1, 'basic-page');

// What can you do with last modified dates ? Let me show you an example

// Think you are in news page, $page->id is news page id we are using $user->language->id because if we have multi language website
// Here getLastModified() function will get last modified date for us, if news page or children pages have any update new cache data will be created automatically
// Like this you can set expire time 0 unlimited from module panel !
// Think we are in "new-list" template and listing children pages
$keyword = "newsPage" . $page->id . $user->language->id . $AvbFastCache->getLastModified($page->id, 'news-single');

// Load library with your settings
$_c3 = phpFastCache($AvbFastCache->storage, $AvbFastCache->getConfig(), $AvbFastCache->expire);

// Write to Cache and Display Result
echo $_c3->set($keyword, function($page)) {

    $output = "";

    foreach($page->children as $p) $output .= "<h2>{$p->title}</h2>";

    return $output;
});

You can check phpfastcache usage from phpfastcache wiki or phpfastcache offical website

Note : I didn't tested this module with older ProcessWire versions, tested with 2.6.1 or newer versions. Module not have core dependency, it could work also older versions but need to check for be sure !

  • Like 7

Share this post


Link to post
Share on other sites

With ProcessWire 2.6.7 or newer version, You can do something like :
 
ready.php, simple example, you can extent this may i missed something and you can have better idea for best caching methods..

// You can set your site templates for cache or ignore cache
$allowedCacheTemplate = array(
        'home',
        'basic-page',
        'contact' => array(
            'ignore' => true
        ),
        'reference',
        'reference-list' => array(
            'list' => true,
            'childTemplate' => 'reference',
            'pagination' => true
        ),
        'service-list' => array(
            'pagination' => true
        )
    );

    wire()->addHook("Page::render", function(HookEvent $event) use($page, $user, $input, $allowedCacheTemplate) {
        $template = $event->template;

        // Check allowed cache templates, if template has ignore or don't have template return $event->return;
        if(isset($allowedCacheTemplate[$template]['ignore']) || !isset($allowedCacheTemplate[$template])) return $event->return;

        // Start Caching
        $avbfastcache = wire('modules')->get('AvbFastCache');
        $_c = phpFastCache($avbfastcache->storage, $avbfastcache->getConfig(), $avbfastcache->expire);
        // Set default keyword
        $keyword = $template . $page->id . $page->modified . $user->language->id;
        // For list view, get children last modified unix time and add it to $keyword
        if(isset($allowedCacheTemplate[$template]['list'])) {
            $filterTemplte = (isset($allowedCacheTemplate[$template]['childTemplate'])) ? $allowedCacheTemplate[$template]['childTemplate'] : NULL;
            $getLastModified = $avbfastcache->getLastModified($page->id, $filterTemplte);
            $keyword .= $getLastModified;
        }
        // If there is a pagination on this template also add $input->pageNum to template
        if(isset($allowedCacheTemplate[$template]['pagination'])) {
            $keyword .= $input->pageNum;
        }
        // Out keyword is ready to use, check cache exist?
        $html = $_c->get($keyword);
        // If cache not exist create cache
        if($html == null) {
            $html = $event->return;;
            $_c->set($keyword, $html);
        }
        // return the result
        return $html;
    });

With this method you can cache template before render !

  • Like 1

Share this post


Link to post
Share on other sites

@ukyo, thanks for this! Looks very cool, and I'll be psyched to test this at some point soon...

Share this post


Link to post
Share on other sites

I updated Hook for ProcessPageSort::execute function and added some useful options. Now you have options for sorted pages.

post-2064-0-39739400-1436662959_thumb.pn

Share this post


Link to post
Share on other sites

what is the advantage over using the built-in cache or procache?

Share this post


Link to post
Share on other sites

what is the advantage over using the built-in cache or procache?

ProCache is a paid version cache module ! Do not compare this free module with paid modules but if you know how to extend module you can do it like ProCache or better than it !

Build-in cache module is only support database cache, on the templates side its support files cache but you can't use it for custom uses. I used both of them there is no place for expire time set option, cached data info or clear cache section etc..

If you check  phpfastcache offical website you will see advantages of using this module. For example you can use multiple cache drivers in same time with different options or you can set a default options for use any where. You can set expire date, you can clear cached data (for files, sqllite drivers), and you can set the what need to do after a page modified etc.....

Here is my website : http://altivebir.com/ using this cache module.

post-2064-0-66734800-1437383025_thumb.pn

  • Like 1

Share this post


Link to post
Share on other sites

Hi @ukyo

I want to use your AVBfastcache module in my new project but can't find any information about its capability with PW 3.

Also, there is no activity in repo and forum more than a year, so I'm curious about your plans to maintain this module.

Share this post


Link to post
Share on other sites
19 hours ago, Zeka said:

Hi @ukyo

I want to use your AVBfastcache module in my new project but can't find any information about its capability with PW 3.

Also, there is no activity in repo and forum more than a year, so I'm curious about your plans to maintain this module.

I will update module with latest phpFastCache (v6). I think this update will come next month.

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Robin S
      Breadcrumb Dropdowns
      Adds dropdown menus of page edit links to the breadcrumbs in Page Edit.

      Installation
      Install the Breadcrumb Dropdowns module. The module requires ProcessWire >= v3.0.83 and AdminThemeUikit.
      There is a checkbox option in the module config that determines if the breadcrumb dropdowns will include pages that the user does not have permission to edit.
      Features/details
      The module adds an additional breadcrumb item at the end for the currently edited page. That's because I think it's more intuitive for the dropdown under each breadcrumb item to show the item's sibling pages rather than the item's child pages. In the dropdown menus the current page and the current page's parents are highlighted in a crimson colour to make it easier to quickly locate them in case you want to edit the next or previous sibling page. If the option to include uneditable pages is selected then those pages are indicated by a reduced text opacity and the "not-allowed" cursor is shown on hover. There is a limit of 25 sibling pages per dropdown for performance reasons and to avoid the dropdown becoming unwieldy. Incompatibilities
      This module replaces the AdminThemeUikit::renderBreadcrumbs method so will potentially be incompatible with other modules that hook the same method.
      Known incompatible modules:
      AdminThemeBoss  
      https://modules.processwire.com/modules/breadcrumb-dropdowns/
      https://github.com/Toutouwai/BreadcrumbDropdowns
    • By joshuag
      Hey guys, 
      Thought I would share a quick preview of Designme. A module we (Eduardo @elabx and I) are building for visually laying out your templates/edit screens. 🙂
      This is a really quick, zero polish screen grab. FYI. 
      Video #2 - UPDATE
      This new video shows the following features in Designme:
      Re-arranging fields via Drag & Drop Re-sizing fields via Dragging. Adjusting field settings - with live refresh. Working on "hidden" fields while Designme is active. Creating New fields. Deleting fields. Creating/Deleting Tabs. Dragging fields between tabs. Creating fieldsets. Tagging/Un-tagging fields. Fields without headers expand when hovered (like checkboxes). Live filtering of fields in the sidebar. Ability to adjust (all) Template settings without leaving Designme. Template File Tree Editing Template files source code with ACE Editor. Editing Multiple files with ACE Editor. (New Tabs) Saving files. Techie stuff Fields load their own js/css dependancies. *ready to use on creation (*most fields)  Everything happens via Ajax to ProcessPageEdit (via module + hooks). Designme has a JS api that you can use.  All actions trigger events.  We would love any detailed feedback on what you see so far. If you are interested in testing Designme. Let me know below. 🙂
       
       
      Video #1. 
       
    • By dreerr
      TemplateEnginePug (formally TemplateEngineJade)
       
      This module adds Pug templates to the TemplateEngineFactory. It uses https://github.com/pug-php/pug to render templates.
      doctype html html(lang='en') head meta(http-equiv='content-type', content='text/html; charset=utf-8') title= $page->title link(rel='stylesheet', type='text/css', href=$config->urls->templates . 'styles/main.css') body include header.pug h1= $page->title if $page->editable() p: a(href=$page->editURL) Edit Project on GitHub: github.com/dreerr/TemplateEnginePug
      Project in modules directory: modules.processwire.com/modules/template-engine-pug/
       
      For common problems/features/questions about the Factory, use the TemplateEngineFactory thread.
       
    • By tpr
      ProcessNetteTester
      Run Nette Tester tests within ProcessWire admin.
      (continued from here)

      Features
      AJAX interface for running Nette Tester tests, in bulk or manually display counter, error message and execution time in a table run all tests at once or launch single tests show formatted test error messages and report PHP syntax errors stop on first failed test (optional) hide passed tests (optional) display failed/total instead passed/total (optional) re-run failed tests only (optional) auto scroll (optional) include or exclude tests based on query parameters start/stop all tests with the spacebar reset one test or all tests (ctrl+click) https://modules.processwire.com/modules/process-nette-tester/
      https://github.com/rolandtoth/ProcessNetteTester
    • By bernhard
      Some of you might have followed the development of this module here: https://processwire.com/talk/topic/15524-previewdiscussion-rockdatatables/ . It is the successor of "RockDataTables" and requires RockFinder to get the data for the grid easily and efficiently. It uses the open source part of agGrid for grid rendering.
       
      WHY?
      ProcessWire is awesome for creating all kinds of custom backend applications, but where it is not so awesome in my opinion is when it comes to listing this data. Of course we have the built in page lister and we have ListerPro, but none of that solutions is capable of properly displaying large amounts of data, for example lists of revenues, aggregations, quick and easy sorts by the user, instant filter and those kind of features. RockGrid to the rescue 😉 
       
      Features/Highlights:
      100k+ rows Instant (client side) filter, search, sort (different sort based on data type, eg "lower/greater than" for numbers, "contains" for strings) extendable via plugins (available plugins at the moment: fullscreen, csv export, reload, batch-processing of data, column sum/statistics, row selection) all the agGrid features (cell renderers, cell styling, pagination, column grouping etc) vanilla javascript, backend and frontend support (though not all plugins are working on the frontend yet and I don't plan to support it as long as I don't need it myself)  
      Limitations:
      While there is an option to retrieve data via AJAX the actual processing of the grid (displaying, filtering, sorting) is done on the client side, meaning that you can get into troubles when handling really large datasets of several thousands of rows. agGrid should be one of the most performant grid options in the world (see the official example page with a 100k row example) and does a lot to prevent problems (such as virtual row rendering), but you should always have this limitation in mind as this is a major difference to the available lister options that do not have this limitation.
      Currently it only supports AdminThemeUikit and I don't plan to support any other admin theme.
       
      Download: https://gitlab.com/baumrock/RockGrid
      Installation: https://gitlab.com/baumrock/RockGrid/wikis/Installation
      Quikckstart: https://gitlab.com/baumrock/RockGrid/wikis/quickstart
      Further instructions: https://gitlab.com/baumrock/RockGrid/wikis/quickstart#further-instructions
       
      Module status: alpha, License: MIT
      Note that every installation and uninstallation sends an anonymous google analytics event to my google analytics account. If you don't want that feel free to remove the appropriate lines of code before installation/uninstallation.
       
      Contribute:
      You can contribute to the development of this and other modules or just say thank you by
      testing, reporting issues and making PRs at gitlab liking this post buying me a drink: paypal.me/baumrock/5 liking my facebook page: facebook.com/baumrock hiring me for pw work: baumrock.com  
      Support: Please note that this module might not be as easy and plug&play as many other modules. It needs a good understanding of agGrid (and JavaScript in general) and it likely needs some looks into the code to get all the options. Please understand that I can not provide free support for every request here in the forum. I try to answer all questions that might also help others or that might improve the module but for individual requests I offer paid support for 60€ per hour.
       
      Changelog
      180711 bugfix (naming issue) 180630 alpha realease  
      Use Cases / Examples:
      Colored grid cells, Icons, Links etc. The Grid also has a "batcher" feature built in that helps communicating with the server via AJAX and managing resource intensive tasks in batches:

      Filters, PW panel links and instant reload on panel close:

      You can combine the grid with a chart library like I did with the (outdated) RockDataTables module: