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
Related
Coming from Yii2 at the end of each request when something is logged, Yii2 adds additional data to your log, for example the $_POST data so you know what paramaters caused the issue.
Is there a way to add these information in Monolog too?
I don't want to use a Processor as it includes all those parameters to each and every record. I would just like to add an additional string in case something is logged at the end of the log after all messages are included/send (for example via BufferHandler when sending Mails via SwiftMailerHandler)
I found a way..
I can extend the default HtmlFormatter or LineFormatter and include my custom information that way
namespace modules\myspa\monolog;
class HtmlFormatter extends \Monolog\Formatter\HtmlFormatter
{
public function formatBatch(array $records): string
{
$formatBatch = parent::formatBatch($records);
$formatBatch .= '<br><br>Foobar.. add some custom info';
return $formatBatch;
}
}
Then I can add this one as a formatter
$swiftMailHandler = new SwiftMailerHandler($swiftMailer, $message, \Monolog\Logger::ERROR);
// add my formatter
$swiftMailHandler->setFormatter(new HtmlFormatter());
$psrLogger->pushHandler(new BufferHandler($swiftMailHandler));
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.
I have a form that submits to the submit_ajax method when submitted via AJAX. Now, when I receive it as an AJAX request, I want to return a JSON object.
In this case, I have two options. What would be considered the right way to do it, following the MVC pattern?
Option 1
Echo it from the controller
class StackOverflow extends CI_Controller
{
public function submit_ajax()
{
$response['status'] = true;
$response['message'] = 'foobar';
echo json_encode($response);
}
}
Option 2 Set up a view that receives data from the controller and echoes it.
class StackOverflow extends CI_Controller
{
public function submit_ajax()
{
$response['status'] = true;
$response['message'] = 'foobar';
$data['response'] = $response;
$this->load->view('return_json',$data);
}
}
//return_json view
echo json_encode($response);
The great thing about CodeIgniter is that in most cases it's up to yourself to decide which one you're more comfortable with.
If you (and your colleges) prefer to echo through the Controller, go for it!
I personally echo ajax replies through the Controller cause it's easy and you have all of your simple scripts gathered, instead of having to open a view file to confirm an obivous json_encode().
The only time I'd see it to be logical to use view in this case is if you have 2 view files that echo's json and XML for instance. Then it can be nice to pass the same value to these views and get different outcome.
The correct way according to the MVC pattern is to display data in the View. The Controller should not display data at any case.
MVC is often seen in web applications where the view is the HTML or
XHTML generated by the application. The controller receives GET or
POST input and decides what to do with it...
source: http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
Usually when you have to show something on success in ajax funnction you need flags means some messages. And according to those messages you display or play in success function . Now there is no need to create an extra view. a simple echo json_encode() in controller is enough. Which is easy to manipulate.
I am in the process of learning the MVC pattern and building my own lightweight one in PHP
Below is a basic example of what I have right now.
I am a little confused on how I should handle AJAX requests/responses though.
In my example user controller below, If I went to www.domain.com/user/friends/page-14 in the browser, it would create a User object and call the friends method of that object
The friends method would then get the data needed for the content portion of my page.
My app would load a template file with a header/footer and insert the content from the object above into the middle of the page.
Now here is where I am confused, if a request is made using AJAX then it will call a page that will do the process over, including loading the template file. IF an AJAX call is made, I think it should somehow, just return the body/content portion for my page and not build the header/footer stuff.
So in my MVC where should I build/load this template file which will have the header/footer stuff? ANd where should I detect if an AJAX request is made so I can avoid loading the template?
I hope I am making sense, I really need help in figuring out how to do this in my MVC I am building. IUf you can help, please use some sample code
/**
* Extend this class with your Controllers
* Reference to the model wrapper / loader functions via $this->model
* Reference to the view functions via $this->view
*/
abstract class Core_Controller {
protected $view;
protected $model;
function __construct(DependencyContainer $dependencyContainer){
$this->view = new Core_View();
//$this->view = $dependencyContainer->get(view);
}
public function load($model){
//load model
//this part under construction and un-tested
$this->$model = new $model;
}
}
user controller
/**
* Example Controller
*/
class User_Controller extends Core_Controller {
// domain.com/user/id-53463463
function profile($userId)
{
//GET data from a Model
$profileData = $this->model->getProfile($userId);
$this->view->load('userProfile', $profileData);
}
// domain.com/user/friends/page-14
function friends()
{
//GET data from a Model
$friendsData = $this->model->getFriends();
$this->view->load('userFriends', $friendsData);
}
}
For me, I developed a separate object that handles all template display methods. This is good because you can then ensure that all the resources you need to display your UI is contained in one object. It looks like you've isolated this in Core_View.
Then, when an AJAX call is made, simply detect that it is an AJAX call. This can be done by either making the AJAX call through an AJAX object, which then references other objects, or you can take an easy approach and simply set an extra POST or GET field which indicates an AJAX call.
Once you've detected if it's an AJAX call, define a constant in your MVC such as AJAX_REQUEST. Then, in your template/UI object, you can specify that if it's an AJAX call, only output your response text. If it isn't, proceed with including your template files.
For me, I send it through an AJAX object. That way I don't have to worry about making a single output work for both cases. When it's ready to send a response, I just do something to the manner of print( json_encode( ...[Response]... ) ).
well, it would all start with normal request which would load the initial page. there are many options as to handle this but let's say that you start with /users/friends page which would list all your friends. then each of the friends should have link to specific friend's profile -- now this is the moment where ajax could kick in and you could ajaxify links to your friend profiles - this means that instead of normal you would instead use let's say jQuery and setup click handler in a such way that
$("a").click(function(){$.post($(this).attr("href"), null, function(data){$("#content").html(data);}});
this would use "href", and upon click would make post request to your backend. at backend, if you see that it's post, then you would just return the content for that particular friend. alternatively, if you have get request, you return all - header - content - footer.
if you use technique above, make sure to properly handle the data you receive. e.g. if there are further actions that should be done via ajax, make sure to "ajaxify" the data you get back. e.g. after updating html of the content, again apply the $("a").click routine.
this is just trivial example, to kick you off, but there are many more sophisticated ways of doing that. if you have time, I suggest reading some of agiletoolkit.org, it has nice mvc + ajax support.
You will need to use a different view. Maybe something like:
funciton friends() {
$this->view = new Ajax_Request_View();
$friendsData = $this->model->getFriends();
$this->view->load($friendsData);
}
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.