flash_set, flash_get in PHP? - php

so i got told in this question:
PHP/Javascript passing message to another page
to use flash_set and flash_get, concept called "Rails flash".. Now can you use them in php those function? I can really find them in php library site, so im not sure..

You can store the messages you want to flash on the next page request in the $_SESSION. I don't know exactly how the methods work in rails but hopefully these two functions can be of use:
function flash_get()
{
// If there are any messages in the queue
if(isset($_SESSION['flashMessages']))
{
// Fetch the message queue
$messages = $_SESSION['flashMessages'];
// Empty out the message queue
unset($_SESSION['flashMessages']);
return $messages;
}
// No messages so just return an empty array
return array();
}
function flash_set($message)
{
// If the queue is currently empty we need to create an array
if(!isset($_SESSION['flashMessages'])) {
$_SESSION['flashMessages'] = array();
}
// Fetch the current list of messages and append the new one to the end
$messages = $_SESSION['flashMessages'];
$messages[] = $message;
// Store the message queue back in the session
$_SESSION['flashMessages'] = $messages;
}
Just call flash_set() with the message you want to store and flash_get() will give you that array back and flush the queue on a later page request.
You'll have to make sure as well that you call session_start() with every page request for these methods to work.

There's no a built-in function in PHP to achieve this, but if you use some frameworks as CakePHP (which is inspired on rails), you'll find it quite simple:
// In the controller
$this->Session->setFlash('message to flash');
// In the view
$session->flash();
I bet some other frameworks have this covered.

Related

Is there a way to automatically unset a variable after accessing in php?

I am trying to display success or failure messages using session variables. I want them to be unset once the session variable once it is accessed. Is there some kind of PHP configuration where I can do it automatically with out writing any extra code?
I want something like this:
$_SESSION['message'] = 'print success';
echo $_SESSION['message'];
unset($_SESSION['message'])// I want this to be done automatically.
Could somebody help me with this?
You can write your own session handler and have a custom method for that. I strongly suggest Illuminate/Session, though, and use it's flash feature which keeps items in flash bag for the duration of one request only.
class Session {
public function read($str){
return isset($_SESSION[$str]) ? $this->deleteAndRet($str) : null;
}
protected function deleteAndRet($str){
$ret = $_SESSION[$str];
unset($_SESSION[$str]);
return $ret;
}
}

How to efficiently fire an event each time a different page is accessed

im working on an application from my companies previous developer and im at the point now where the boss has asked me to log which user has accessed what page. So I've set up some events and listeners to get the job done as i have been doing for all the other logs but there is a problem.
If i was to fire an event the way I've been doing it up till now id have to re-write the code to fire an event for every separate method that returns a page, but right now this is the only viable option i see because then i can customise the information that i put into the event log (I need the ability to customise information that's being pushed to the event / listener). Example Below
public function showCreateAccount()
{
// NEW EVENT HERE
//I need the account types for this page and the status types
$account_types = AccountController::getTypes();
$status_types = StatusController::getTypes();
$timezone_types = TimezoneController::getTypes();
$currency_types = CurrencyController::getTypes();
return view('create.account')->with('account_types', $account_types)
->with('status_types', $status_types)
->with('currency_types', $currency_types)
->with('timezone_types', $timezone_types);
}
public function showCreateRevenue()
{
// NEW EVENT HERE...
$revenue_types = RevenueController::getTypes();
return view('create.income')->with('revenue_types', $revenue_types);
}
public function showCreateIncomeWithID($id)
{
// NEW EVENT HERE
return view('create.income')->with('account_id', $id);
}
public function showCreateExpense()
{
// NEW EVENT HERE, ETC ETC
$expense_types = ExpenseController::getTypes();
return view('create.outcome')->with('expense_types', $expense_types);
}
Now this will work fine i assume but what im worried about is that this method isnt "good practice" surely there must be an alternative to writing a new event in each and every function whilst still being able to pass relevant information about what page has been accessed?
If i am wrong please correct me if not your answers are welcome

Zend framework 1 flash messenger yields empty array

I'm trying to set a message in Zend Framework 1's flash messenger. Then I'm outputting the result here as I was getting nothing in my view:
public function successAction()
{
$this->_helper->flashMessenger->addMessage('Account has been successfully created.');
$this->view->messages = $this->_helper->flashMessenger->getMessages();
var_dump($this->view->messages); exit;
}
..but it's just an empty array. Is there anything else I have to do withing the framework, or with the helper to set and retrieve these?
Here is how I was trying to access it from
The FlashMessenger helper allows you to pass messages that the user
may need to see on the next request. To accomplish this,
FlashMessenger uses Zend_Session_Namespace to store messages for
future or next request retrieval.
You can see it in the doc
So your message can be recovered in another action (other request).
If you want to retrieve the message in the same action, you can try to use getCurrentMessages():
$this->view->messages = this->_helper->flashMessenger->getCurrentMessages();
But if this message is only for one request, you can use Zend_Registry

Doing an Ajax GET request to return data to PHP

I want to make an Ajax search request agains an API and get the data returned to my PHP file, right now I'm using Javascript and jQuery to do the job. But I want to let PHP do all the job, simply because I don't want my API key to be public and I may want to cash the data in a database further on. It seems that it should be simple, but I just can't figure out how to do it clean, call javascript and return or how to "integrate" it with PHP.
I am doing my PHP in the MVC pattern, like so:
Controller called from "mastercontroller/index":
class SearchController {
public function DoControl($view, $model) {
$ret = "";
$ret .= $view->GetSearchForm();
if($view->TriedToSearch()) {
if($view->GetSearchString()) {
$ret .= $model->CheckSearchString($view->GetSearchString());
} else {
// Didn't search for anything
}
} else {
// Didn't press the search button
}
return $ret;
}
}
My view is returning an HTML form, checking if submit is pressed and also returning the searchstring, that I am sending in to my Model above.
Model:
class SearchModel {
public function CheckSearchString($searchString) {
// 1. Call Googlebooks api with the searchstring
// 2. Get JSON response to return to the controller
// 3. The controller sends the data to the View for rendering
}
}
I just can't figure out how I should do it.
I'm not entirely sure, but you seem to be asking how to perform an AJAX request without JavaScript. You can't do that -- it's not possible to use the XmlHttpRequest object without JavaScript. That's, according to legend, the origin of the "J" in the AJAX name.
It sounds like you need to use REST to call specific API's. RESTful state allows you to use web services to return specific data according to a predefined API. Data can be returned in XML or JSON.
You can do this very easily with PHP's cURL implementation using whatever keys Google gives you.
See Google's Google Books API Family page for links to PHP API and sample code.
Would the below practice be useful to you? If you just want to implement ajax functionality in your code.
Simple AJAX - PHP and Javascript
I am sorry for mistaking the content. How about the two below:
simple http request example in php
PHP HTTP-Request * from another stackoverflow question
But I think ajax is main in client program meaning. At the server-side, just call it http request.

Best way to carry & modify a variable through various instances and functions?

I'm looking for the "best practice" way to achieve a message / notification system. I'm using an OOP-based approach for the script and would like to do something along the lines of this:
if(!$something)
$messages->add('Something doesn\'t exist!');
The add() method in the messages class looks somewhat like this:
class messages {
public function add($new) {
$messages = $THIS_IS_WHAT_IM_LOOKING_FOR; //array
$messages[] = $new;
$THIS_IS_WHAT_IM_LOOKING_FOR = $messages;
}
}
In the end, there is a method in which reads out $messages and returns every message as nicely formatted HTML.
So the questions is - what type of variable should I be using for $THIS_IS_WHAT_IM_LOOKING_FOR?
I don't want to make this use the database. Querying the db every time just for some messages that occur at runtime and disappear after 5 seconds just seems like overkill.
Using global constants for this is apparently worst practice, since constants are not meant to be variables that change over time. I don't even know if it would work.
I don't want to always pass in and return the existing $messages array through the method every time I want to add a new message.
I even tried using a session var for this, but that is obviously not suited for this purpose at all (it will always be 1 pageload too late).
Any suggestions?
Thanks!
EDIT: Added after I caused some confusion with the above...
The $messages array should be global: I need to be able to add to it through various different classes as well as at the top-level of the whole script.
The best comparison that comes to mind is to use a database to store all the messages that occur at runtime, and when it's output-time, query the database and output every message. The exception to this comparison is just that the lifetime of the $messages array is the page load (they accumulate during page load, and vanish right after).
So, for example, say I have 10 different actions running one after the other in the script. Each one of these actions make use of a different class. Each one of these classes should be able to post to $messages->add(). After all 10 actions have run, it's "output time", and the $messages array can contain up to 10 different messages which were added via all the different classes.
I hope this clarifies it a bit.
I'm not exactly clear about what you want to do, but a good way would be to simply use a private variable:
class messages {
private $messages = array();
public function add($new) {
$this->messages[] = $new;
}
public function output() {
// Whatever; e.g. a foreach loop that echoes all the messages
}
}
I think you need either a instance field.

Categories