How can we override cache_set() in drupal 7 - caching

I have a drupal 7 application. I need to block the insertion of cache in cache_form table. So how can we override cache_set() in drupal 7?

You can't override cache_set(), what you can do is use a custom cache backend for the cache_form cache bin. If you don't want to cache anything for cache_form, you can use a simple implementation whose methods do nothing.
class DoNothingCache extends DrupalCacheInterface {
/**
* {#inheritdoc}
*/
function get($cid) {
return FALSE;
}
/**
* {#inheritdoc}
*/
function getMultiple(&$cids) {
return array();
}
/**
* {#inheritdoc}
*/
function set($cid, $data, $expire = CACHE_PERMANENT) {}
/**
* {#inheritdoc}
*/
function clear($cid = NULL, $wildcard = FALSE) {}
/**
* {#inheritdoc}
*/
function isEmpty() {
return TRUE;
}
}
The cache_class_cache_form configuration variable defines the class, implementing the DrupalCacheInterface interface, to use for the cache_form bin. You can set it in your settings.php file.
$conf['cache_class_cache_form'] = 'DoNothingCache';

Related

What is the best way for reusable values throughout the application in Symfony 3?

I want to have a file or list that I can update easily with values that might change throughout my application.
I don't really want to hard code text values into the templates. I prefer to have all of these values in one place and labelled correctly.
Examples of values that might get updated are:
Page title
Logo text
Brand or company name
I have thought about two options:
Add them to the twig config in config.yml. This is a bit messy and doesn't seem organised if I decide to put a lot of values there.
Make a database table for these and include the entity in each controller where I need to use the values. This might be creating too much work.
Are there any other options or are one of these more suitable?
Thank you.
You need to create a twig function and use it to return the value you want. For example:
namespace AppBundle\Twig;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
class TwigExtension extends \Twig_Extension implements ContainerAwareInterface
{
use ContainerAwareTrait;
/**
* #var ContainerInterface
*/
protected $container;
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('parameter', function($name)
{
try {
return $this->container->getParameter($name);
} catch(\Exception $exception) {
return "";
}
})
);
}
/**
* Returns the name of the extension.
*
* #return string The extension name
*/
public function getName()
{
return 'app.twig.extension';
}
}
This will create a function called parameter and once you call it in twig {{ parameter('my.parameter') }} it will return the parameter. You need to load it as a service, which you can do by adding the following to your services.yml file:
app.twig.extension:
class: AppBundle\Twig\TwigExtension
calls:
- [setContainer, ["#service_container"]]
tags:
- { name: twig.extension }
From personal experience people usually want to be able to change some of the parameters. This is why I usually prefer to create a Setting or Parameter entity which would look something like this:
/**
* Setting
*
* #ORM\Table(name="my_parameters")
* #ORM\Entity(repositoryClass="AppBundle\Repository\ParameterRepository")
*/
class Parameter
{
/**
* #var integer
*
* #ORM\Id
* #ORM\Column(name="parameter_id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="value", type="text", nullable=true)
*/
private $value;
/**
* #param string|null $name
* #param string|null $value
*/
public function __construct($name = null, $value = null)
{
$this->setName($name);
$this->setValue($value);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Parameter
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set value
*
* #param string $value
*
* #return Parameter
*/
public function setValue($value = null)
{
$this->value = serialize($value);
return $this;
}
/**
* Get value
*
* #return string
*/
public function getValue()
{
$data = #unserialize($this->value);
return $this->value === 'b:0;' || $data !== false ? $this->value = $data : null;
}
}
Then I would add a CompilerPass which will help get all of the parameters from the database and cache them so that your app doesn't make unnecessary sql queries to the database. That might look something similar to the following class:
// AppBundle/DependencyInjection/Compiler/ParamsCompilerPass.php
namespace AppBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class ParamsCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$em = $container->get('doctrine.orm.default_entity_manager');
$settings = $em->getRepository('AppBundle:Parameter')->findAll();
foreach($settings as $setting) {
// I like to prefix the parameters with "app."
// to avoid any collision with existing parameters.
$container->setParameter('app.'.strtolower($setting->getName()), $setting->getValue());
}
}
}
And finally, in your bundle class (i.e. src/AppBundle/AppBundle.php) you add the compiler pass:
namespace AppBundle;
use AppBundle\DependencyInjection\Compiler\ParamsCompilerPass;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AppBundle extends Bundle
{
public function build(ContainerBuilder $builder)
{
parent::build($builder);
$builder->addCompilerPass(new ParamsCompilerPass(), , PassConfig::TYPE_AFTER_REMOVING);
}
}
Now you can create a DoctrineFixture template to load the parameters you use all the time. With the TwigExtension you will still be able to call the parameter from the twig template and you can create a web UI to change some of the parameters/settings.

Laravel5 extend Facade

I want to extend Laravel5 Cookies functionality.
I want to make it this way:
I will create file App\Support\Facades\Cookie.php and than file App\Libraries\CookieJar.php. In app.php I will change row for Cookie to this:
'Cookie' => 'App\Support\Facades\Cookie',
Anyway, when I try to use it like this:
Cookie::test()
it returns:
Call to undefined method Illuminate\Cookie\CookieJar::test()
Do you have any idea, why it do this? And is the way, how I want to extend Cookie functionality good?
Thank you for your help.
Here is content of files:
Cookie.php:
<?php namespace App\Support\Facades;
/**
* #see \App\Libraries\CookieJar
*/
class Cookie extends \Illuminate\Support\Facades\Facade
{
/**
* Determine if a cookie exists on the request.
*
* #param string $key
* #return bool
*/
public static function has($key)
{
return !is_null(static::$app['request']->cookie($key, null));
}
/**
* Retrieve a cookie from the request.
*
* #param string $key
* #param mixed $default
* #return string
*/
public static function get($key = null, $default = null)
{
return static::$app['request']->cookie($key, $default);
}
/**
* Get the registered name of the component.
*
* #return string
*/
protected static function getFacadeAccessor()
{
return 'cookie';
}
}
CookieJar.php:
<?php namespace App\Libraries;
class CookieJar extends \Illuminate\Cookie\CookieJar
{
public function test() {
return 'shit';
}
}
The class with all your new cookie functions need to extend Illuminate\CookieJar\CookieJar
<?php
namespace App\Support\Cookie;
class CookieJar extends \Illuminate\Cookie\CookieJar
{
/**
* Determine if a cookie exists on the request.
*
* #param string $key
* #return bool
*/
public static function has($key)
{
return !is_null(static::$app['request']->cookie($key, null));
}
/**
* Retrieve a cookie from the request.
*
* #param string $key
* #param mixed $default
* #return string
*/
public static function get($key = null, $default = null)
{
return static::$app['request']->cookie($key, $default);
}
}
Then make a new facade:
namespace App\Support\Facades;
class CookieFacade extends \Illuminate\Support\Facades\Facade
{
protected static function getFacadeAccessor()
{
/*
* You can't call it cookie or else it will clash with
* the original cookie class in the container.
*/
return 'NewCookie';
}
}
Now bing it in the container:
$this->app->bind("NewCookie", function() {
$this->app->make("App\\Support\\Cookie\\CookieJar");
});
Finally add the alias in your app.php config:
'NewCookie' => App\Support\Facades\CookieFacade::class
Now you can use NewCookie::get('cookie') and NewCookie::has('cookie').
I hope this helps.

Typo3 Extbase Set and Get values from Session

I am writing an extbase extension on typo3 v6.1
That extension suppose to do a bus ticket booking.
Here what my plan is, user will select date and number of seats and submit the form.
Here my plan to push the date and rate of the selected seat to session (Basket).
And while making payment, I wanted to get that values from session and after payment I need to clear that particular session.
So In short, How to Push and retrieve the values to and from the session in extbase.
Any suggestions ?
Thank you.
There are different ways. The simplest would be for writing in the session
$GLOBALS['TSFE']->fe_user->setKey("ses","key",$value)
and for reading values from the session
$GLOBALS["TSFE"]->fe_user->getKey("ses","key")
I'm using for this a service class.
<?php
class Tx_EXTNAME_Service_SessionHandler implements t3lib_Singleton {
private $prefixKey = 'tx_extname_';
/**
* Returns the object stored in the userĀ“s PHP session
* #return Object the stored object
*/
public function restoreFromSession($key) {
$sessionData = $GLOBALS['TSFE']->fe_user->getKey('ses', $this->prefixKey . $key);
return unserialize($sessionData);
}
/**
* Writes an object into the PHP session
* #param $object any serializable object to store into the session
* #return Tx_EXTNAME_Service_SessionHandler this
*/
public function writeToSession($object, $key) {
$sessionData = serialize($object);
$GLOBALS['TSFE']->fe_user->setKey('ses', $this->prefixKey . $key, $sessionData);
$GLOBALS['TSFE']->fe_user->storeSessionData();
return $this;
}
/**
* Cleans up the session: removes the stored object from the PHP session
* #return Tx_EXTNAME_Service_SessionHandler this
*/
public function cleanUpSession($key) {
$GLOBALS['TSFE']->fe_user->setKey('ses', $this->prefixKey . $key, NULL);
$GLOBALS['TSFE']->fe_user->storeSessionData();
return $this;
}
public function setPrefixKey($prefixKey) {
$this->prefixKey = $prefixKey;
}
}
?>
Inject this class into your controller
/**
*
* #var Tx_EXTNAME_Service_SessionHandler
*/
protected $sessionHandler;
/**
*
* #param Tx_EXTNAME_Service_SessionHandler $sessionHandler
*/
public function injectSessionHandler(Tx_EXTNAME_Service_SessionHandler $sessionHandler) {
$this->sessionHandler = $sessionHandler;
}
Now you can use this session handler like this.
// Write your object into session
$this->sessionHandler->writeToSession('KEY_FOR_THIS_PROCESS');
// Get your object from session
$this->sessionHandler->restoreFromSession('KEY_FOR_THIS_PROCESS');
// And after all maybe you will clean the session (delete)
$this->sessionHandler->cleanUpSession('KEY_FOR_THIS_PROCESS');
Rename Tx_EXTNAME and tx_extname with your extension name and pay attention to put the session handler class into the right directory (Classes -> Service -> SessionHandler.php).
You can store any data, not only objects.
HTH
From Typo3 v7 you can also copy the native session handler (\TYPO3\CMS\Form\Utility\SessionUtility) for forms and change it to your needs. The Class makes a different between normal and logged in users and it support multiple session data seperated by the sessionPrefix.
I did the same and generalized the class for a more common purpose. I only removed one method, change the variables name and added the method hasSessionKey(). Here is my complete example:
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
/**
* Class SessionUtility
*
* this is just a adapted version from \TYPO3\CMS\Form\Utility\SessionUtility,
* but more generalized without special behavior for form
*
*
*/
class SessionUtility {
/**
* Session data
*
* #var array
*/
protected $sessionData = array();
/**
* Prefix for the session
*
* #var string
*/
protected $sessionPrefix = '';
/**
* #var TypoScriptFrontendController
*/
protected $frontendController;
/**
* Constructor
*/
public function __construct()
{
$this->frontendController = $GLOBALS['TSFE'];
}
/**
* Init Session
*
* #param string $sessionPrefix
* #return void
*/
public function initSession($sessionPrefix = '')
{
$this->setSessionPrefix($sessionPrefix);
if ($this->frontendController->loginUser) {
$this->sessionData = $this->frontendController->fe_user->getKey('user', $this->sessionPrefix);
} else {
$this->sessionData = $this->frontendController->fe_user->getKey('ses', $this->sessionPrefix);
}
}
/**
* Stores current session
*
* #return void
*/
public function storeSession()
{
if ($this->frontendController->loginUser) {
$this->frontendController->fe_user->setKey('user', $this->sessionPrefix, $this->getSessionData());
} else {
$this->frontendController->fe_user->setKey('ses', $this->sessionPrefix, $this->getSessionData());
}
$this->frontendController->storeSessionData();
}
/**
* Destroy the session data for the form
*
* #return void
*/
public function destroySession()
{
if ($this->frontendController->loginUser) {
$this->frontendController->fe_user->setKey('user', $this->sessionPrefix, null);
} else {
$this->frontendController->fe_user->setKey('ses', $this->sessionPrefix, null);
}
$this->frontendController->storeSessionData();
}
/**
* Set the session Data by $key
*
* #param string $key
* #param string $value
* #return void
*/
public function setSessionData($key, $value)
{
$this->sessionData[$key] = $value;
$this->storeSession();
}
/**
* Retrieve a member of the $sessionData variable
*
* If no $key is passed, returns the entire $sessionData array
*
* #param string $key Parameter to search for
* #param mixed $default Default value to use if key not found
* #return mixed Returns NULL if key does not exist
*/
public function getSessionData($key = null, $default = null)
{
if ($key === null) {
return $this->sessionData;
}
return isset($this->sessionData[$key]) ? $this->sessionData[$key] : $default;
}
/**
* Set the s prefix
*
* #param string $sessionPrefix
*
*/
public function setSessionPrefix($sessionPrefix)
{
$this->sessionPrefix = $sessionPrefix;
}
/**
* #param string $key
*
* #return bool
*/
public function hasSessionKey($key) {
return isset($this->sessionData[$key]);
}
}
Don't forget to call the initSession first, every time you want use any method of this class

Laravel 4 - Extend Pagination Class

Is there a way to extend the Pagination Class of Laravel 4 ?
I tried some things but nothing good...
I'm here :
PaginationServiceProvider.php
class PaginationServiceProvider extends \Illuminate\Pagination\PaginationServiceProvider {
/**
* Indicates if loading of the provider is deferred.
* #var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
* #return void
*/
public function boot(){
$this->package('thujohn/pagination');
}
/**
* Register the service provider.
* #return void
*/
public function register(){
$this->app['paginator'] = $this->app->share(function($app){
$paginator = new Environment($app['request'], $app['view'], $app['translator']);
$paginator->setViewName($app['config']['view.pagination']);
return $paginator;
});
}
/**
* Get the services provided by the provider.
* #return array
*/
public function provides(){
return array();
}
}
Environment.php
class Environment extends \Illuminate\Pagination\Environment {
public function hello(){
return 'hello';
}
}
I replaced 'Illuminate\Pagination\PaginationServiceProvider', by 'Thujohn\Pagination\PaginationServiceProvider',
When I call $test->links() it's ok
When I call $test->hello() it fails
When I call Paginator::hello() it's ok
Any idea ?
Everyting is fine except that Paginator::make() returns Paginator instance, not Environment.
You should move Your method to Paginator class.
Today I've posted on GH my extension for Paginator. You can check it as a reference desmart/pagination

Doctrine 1.* cache invalidation

I'm using APC cache for expensive query which retrieve job with related files, payments, events etc.
I would like to know if there are available solutions for cache invalidation in Doctrine 1.*.
I came up with following working solution, it does work, I just don't want to invent a wheel.
Please suggest me if there are better/other existing solutions.
Record listener tries to clear cache with given id's on postSave event:
class My_Doctrine_Record_Listener_ClearCache extends Doctrine_Record_Listener
{
/**
* Clear cache by table tags
*
* #param Doctrine_Event $event
* #return null
*/
public function postSave(Doctrine_Event $event)
{
$cache = new Doctrine_Cache_Apc();
/* #var $model Doctrine_Record */
$model = $event->getInvoker();
$name = get_class($model);
/* #var $table Doctrine_Table */
$table = $model->getTable($name);
if (method_exists($table, 'getCacheTags')) {
foreach ($table->getCacheTags() as $tag) {
$id = preg_replace('/%([\w]+)%/e', '$model->{\\1}', $tag);
$cache->delete($id);
}
}
}
}
This is what I have in tables:
class FileTable extends Doctrine_Table
{
/* ... */
public function getCacheTags()
{
return array(
'job_view_%job_id%'
);
}
/* ... */
}
class JobTable extends Doctrine_Table
{
/* ... */
public function getCacheTags()
{
return array(
'job_view_%id%'
);
}
/* ... */
}
The above solution has been used for 7 years in the production environment, so it's safe to say - it does work good enough.

Resources