pass global variable between two function on zf2 controller - variables

I should change on zf2 controller a variable global. In practice, I'd like a function to insert the value in the global variable and another function prints the value of the variable. for example:
protected $variablename;
public function setAction()
{
$this->variablename = "hi friends!";
}
public function getAction()
{
var_dump($this->variablename);
}
In this example, when I print the variable I always get NULL.
Any suggestions? tnx
simone

indirectly you can't because of the lifecircle in a zend/php request. after you set up your variable in actionA the variable is reseted if you request actionB
if you want to set your variabel data in actionA and make the data present in actionB you need a persistent save storage (like a db, cookie or session. otherwise it is only possible to forward the current request to another request in your controller. then have a look at the forward controller helper in zend.
http://framework.zend.com/manual/2.3/en/modules/zend.mvc.plugins.html#zend-mvc-controller-plugins-forward
//edit after comment
you can use a session in zend like this
set session
$session = new Zend\Session\Container('base');
$session->offsetSet('someSettings', 'someValue');
get session
$session = new Zend\Session\Container('base');
if( $session->offsetExists('someSettings') )
{
$someSettingValue = $session->offsetGet('someSettings');
}

Related

Using global variable in ASP.NET Core controller

The question is simple but I don't know how use it.
For example there is a controller
public class MainController : Controller
{
private int a;
public IActionResult Index(bool set = true)
{
if (set) a = 10;
return View(a)
}
}
If I get in Index page at first time, I set a = 10. And I get in Index page again (for example refresh Index page or paging in Index page, i.e. move in same page) Actually, I get in Index page with url : ~Index?set=False after first access.
Then the a has 0 (default for int variable). I did not know the Controller page (Controller class) is always initialized when I gen in it even when I move to same page.
So, I want to use variable like global variable not using session.
Is there any way?
It sounds like you wish to persist a variable between requests.
Per user
If you wish to store a variable that persists but is only visible to the current user, use session state:
public int? A
{
get
{
return HttpContext.Current.Session["A"] as int?;
}
set
{
HttpContext.Current.Session["A"] = value;
}
}
Note that we are using int? instead of int in order to handle the case where the session variable has not yet been set. If you prefer to default to 0, you can simply use the coalesce operator, ??.
Truly global
If you wish to persist a variable in a manner where there is only one copy for all users, you can store it in a static variable or in an application state variable.
So either
static volatile public int a;
Or
public int? A
{
get
{
return HttpContext.Current.Application["A"] as int?;
}
set
{
HttpContext.Current.Application["A"] = value;
}
}
Obviously variables that are shared between users can change at any time (due to activity in other threads), so you should be careful about how you handle them. For variables that are int-sized or smaller, the processor will perform atomic reads and writes, but for variables larger than an int you may need to use Interlocked or lock to control access.
You do not need to worry about thread synchronization for session variables; the framework handles it for you.
Note: The above is just an example to help you find the right API. It does not necessarily demonstrate the best pattern-- accessing HttpContext via the static method Current is considered bad form, as it makes it impossible to mock the context. Please see this article for ways to expose it to your code via DI.

Redirect to action passes null instead of object

My MVC4 project uses the RedirectToAction() to pass values to another controller.
The problem is, it passes null instead of a value
[HttpGet]
public ActionResult MyProduct(product prod)
{
return RedirectToAction("Index", "MyController", new { prod = prod});
}
This accurately redirects to my MyController which is
public ActionResult Index(Product prod)
{
// prod is null :(
}
I put on a watch in the MyProduct controller, the prod object has a value. The properties do not have values :( it is null
Why does it become null when I pass the object between controllers?
You mistyped you parameter name that you are expecting at your action change it to prod because the prod is a part of RouteValueDictionary which will be collected by the same parameter as defined askey in the dictionary
return RedirectToAction("Index", "MyController", new { prod = prod});
Update
You cannot pass a model object via route parameters via RedirectToAction if I understood your question correctly, instead you can pass specific properties required to be send or you can use the TempData
You can't send data with a RedirectAction. That's because you're doing a 301 redirection and that goes back to the client.
When you redirect you mainly have the query string as a means to pass data to the other request. The other approach is to use TempData which stores data away on the server and you can retrieve it on the next request. By default TempData uses Session.
Consider this image for getting the ways of passing data between Model-View-Controller
Your function parameter name doesn't match in your RedirectToAction().
You should change it like this:
return RedirectToAction("Index", "MyController", new { prod = prod});

Automatic object cache proxy with PHP

Here is a question on the Caching Proxy design pattern.
Is it possible to create with PHP a dynamic Proxy Caching implementation for automatically adding cache behaviour to any object?
Here is an example
class User
{
public function load($login)
{
// Load user from db
}
public function getBillingRecords()
{
// a very heavy request
}
public function computeStatistics()
{
// a very heavy computing
}
}
class Report
{
protected $_user = null;
public function __construct(User $user)
{
$this->_user = $user;
}
public function generate()
{
$billing = $this->_user->getBillingRecords();
$stats = $this->_user->computeStatistics();
/*
...
Some rendering, and additionnal processing code
...
*/
}
}
you will notice that report will use some heavy loaded methods from User.
Now I want to add a cache system.
Instead of designing a classic caching system, I just wonder if it is possible to implement a caching system in a proxy design pattern with this kind of usage:
<?php
$cache = new Cache(new Memcache(...));
// This line will create an object User (or from a child class of User ex: UserProxy)
// each call to a method specified in 3rd argument will use the configured cache system in 2
$user = ProxyCache::create("User", $cache, array('getBillingRecords', 'computeStatistics'));
$user->load('johndoe');
// user is an instance of User (or a child class) so the contract is respected
$report = new report($user)
$report->generate(); // long execution time
$report->generate(); // quick execution time (using cache)
$report->generate(); // quick execution time (using cache)
each call to a proxyfied method will run something like:
<?php
$key = $this->_getCacheKey();
if ($this->_cache->exists($key) == false)
{
$records = $this->_originalObject->getBillingRecords();
$this->_cache->save($key, $records);
}
return $this->_cache->get($key);
Do you think it is something we could do with PHP? do you know if it is a standard pattern? How would you implement it?
It would require to
implement dynamically a new child class of the original object
replace the specified original methods with the cached one
instanciate a new kind of this object
I think PHPUnit does something like this with the Mock system...
You can use the decorator pattern with delegation and create a cache decorator that accepts any object then delegates all calls after it runs it through the cache.
Does that make sense?

my zend session name spacing does not work

I am new to Zend and very keen to learn, so I would really appreciate some help and guidance.
I am trying to create a 'method in a class' that will save the session variables of product pages visited by members to a site i.e
i,e examplesite com/product/?producttype= 6
I want to save the number 6 in a session variable. I also do not want to have a global session for the entire site; I just want it for selected pages. So, I guess I have to have Zend_Session::start() on the selected page; but I am not clear how this should be done.
Should I instantiate it in the page view page. i.e products page or do this in the indexAction() method for the products page. I have attempted to instantiate it below but it did not work.
public function rememberLastProductSearched()
{ //my attempt to start a session start for this particular page.
Zend_Session::start();
}
$session->productSearchCategory = $this->_request->getParam('product-search-category');
return" $session->productSearchCategory ";
}
else
{
//echo " nothing there
return " $session->productSearchCategory";
//";
}
}
With the rememberLastProductSearched() method I was trying to get the method to first check whether the user had searched for a new product or just arrived at the page by default. i.e whether he had used the get() action to search for a new product. If the answer is no, then I wanted the system to check whether their had been a previous saved session variable. so in procedural syntax it would have gone like this:
if(isset($_Get['producttype']))
{
//$dbc database connection
$producttype = mysqli_real_escape_string($dbc,trim($_GET['producttype']));
}
else
if(isset($_SESSION['producttype'])){
$producttype = mysqli_real_escape_string($dbc,trim($_SESSION['producttype']));
}
Can you please help me with the Zend/oop syntax. I am totally confused how it should be?
you're asking about simple work flow in an action, it should begin something like:
//in any controller
public function anyAction()
{
//open seesion, start will be called if needed
$session = new Zend_Session_Namespace('products');
//get value
$productCategory = $this->getRequest()->getParam('producttype');
//save value to namespace
$session->productType = $productCategory;
//...
}
now to move this off to a separate method you have to pass the data to the method...
protected function rememberLastProductSearched($productType)
{
//open seesion, start will be called if needed
$session = new Zend_Session_Namespace('products');
$session->productType = $productType;
}
So now if you want to test for presence of a value...
//in any controller
public function anyAction()
{
//open seesion, call the namespace whenever you need to access it
$session = new Zend_Session_Namespace('products');
if (!isset($session->productType)) {
$productCategory = $this->getRequest()->getParam('producttype');
//save value to session
$this->rememberLastProductSearched($productCategory)
} else {
$productCategory = $session->productType;
}
}
That's the idea.
Be mindful of your work flow as it can sometimes be very simple to inadvertently overwrite your session values.
$session = new Zend_Session_Namespace("productSearch");
if ($this->getRequest()->getParam('producttype')) { //isset GET param ?
$session->productType = $this->getRequest()->getParam('producttype');
$searchedProductType = $session->productType;
} else { //take the session saved value
if ($session->productType) {
$searchedProductType = $session->productType;
}
}
//now use $searchedProductType for your query

Custom Cookie variable + Prestashop

Prestashop
I am stuck we one problem for cookie. In prestashop 1.4.7 I create a custom cookie variable using setcookie but when i am try to access and assign it on front-controller, I am not getting cookies set value.
here is my script:
page: checkpostcode.php
include(dirname(__FILE__).'/config/config.inc.php');
include(dirname(__FILE__).'/init.php');
global $cookie;
setcookie("is_postcode_checked", 1, time()+600, "/", "", 1); // Set the cookie in basepath
On frontcontroller.php page :
I am access it using $_COOKIE and assign it into smarty array.
'is_postcode_checked' => $_COOKIE['is_postcode_checked'] // Getting null value for cookie
page: checkpostcode.tpl
{$cookie->_get(postcode_checked_msg)} // here get the is_postcode_checked value but
but I am not able to get is_postcode_checked variable value.
In prestashop 1.5, global are deprecated.
To set something in the cookie :
In a controller :
$this->context->cookie->__set($key,$value);
Other file :
$context = Context::getContext();
$context->cookie->__set($finger_print,$result);
You can access to your value with :
In a controller
$this->context->cookie->key
Other file :
$context = Context::getContext();
$context->cookie->key;
You should use Prestashop's own cookie class entirely rather than using the PHP setcookie() function. The class uses the "magic methods" __get(), __set(), __unset() and __isset() which should allow you to do this easily.
Try in your "page" code (not sure how you're executing this since it doesn;t look like an additional page controller):
global $cookie;
$cookie->is_postcode_checked = 1;
$cookie->write(); // I think you'll need this as it doesn't automatically save
...
And in your FrontController override:
global $cookie;
if (isset($cookie->is_postcode_checked))
$is_postcode_checked = $cookie->is_postcode_checked;
else
$is_postcode_checked = 0;
You can assign the variable $is_postcode_checked to a corresponding smarty variable to use in your template.
If you want to fetch the cookie from Prestashop cookie class, you should store it in this class too.
Use die() function in your controller, to find out is that cookie set
It is better, as Paul said, to use only global $cookie class to store and getting data.