Best Practices/How-To for Changing Zend_Session Values with JavaScript - php

I am migrating an old project to Zend Framework. I have a drop down list that changes filter context. In the old project the onClick event of the <select> list ran a function that made a jQuery ajax call to a php script that essentially updated the $_SESSION variable and then the JavaScript reloaded the page when the response came back. I have a couple of questions:
Is this an okay practice?
Should I send the request to a Controller instead of a servlet? One of the issues with this is that the drop down list is built in a view helper and is available across all Controllers, but I understand I could put the necessary code in and have them all inherit it.
If I DO go the stand-alone servlet type route, where do I put the php file in the hierarchy? I'm assuming the public folder- so pardon me if it is a dumb question.
I'm not familiar with Zend_Session, are there any gotchas to watch out for?
--EDIT--
After some initial code testing I have run into an issue with my servlet php file (let's call it registrar.php) is not able to get the Zend_Session_Namespace from the Zend_Registry when it is standalone (I'm not sure if I'm not doing it right, but since it's not being sent through index.php it makes sense to me that it can't access the registry). Instead of registrar.php I'm going to create a RegistrarController

I have created a RegistrarController, disabled the standard layout and view and put my logic in there

Related

Setting and getting session variables in Bolt CMS

I have a web app running on Bolt CMS and I need to be able to save some information across page loads so it's persistent. The data needs to be set via an AJAX call and retrieved within a Twig template. The trouble is, I don't know how I can do this within the Bolt environment (I've never used Symfony before)
I've seen quite a few similar questions on how to retrieve session variables within a Symfony controller but nothing on how to edit (or add a new) controller so that I can call it via AJAX to set the session variable
Thanks
Because twig is rendered server-side, I assume you want to set something in one request, and then fetch it again on the next. I think you will need to create an extension for this, that stores the data in a table, and allows you to fetch it later. Take a look at the "WaffleOrders" extension for a good example on how to do this: https://github.com/bolt/WaffleOrders
This is all happening on the bolt side, though. To make it ajaxy, you should use jquery's ajax functionality to POST or GET the data, as needed.

Beginner CodeIgniter concepts - Reusable view code, where to go? (Helper?)

I am a beginner with CodeIgniter still struggling to get a complete grasp on how to use the MVC ideology most cleanly.
I am writing a basic CMS system with the ability to vote on entries and follow people etc, consequently, I have found myself using the same or similar pieces of code across multiple views here and there consisting of various pieces of html and logic such as:
Voting panel
Follow/Unfollow panel
Login/Logout panel
Code to check if a user is logged in etc...
I am wondering where to put this code so it can be unified? I am thinking a helper is the way to go? If I declare the helper in the controller, it can be called from the corresponding view right?
Some of the elements are dynamic - such as a follow/unfollow button - It would need to check if you are already following the user or not and display the appropriate button, which would require a model to check. What I have now is that all the logic is in the controller and it returns an appropriate button, but it seems weird to be returning formed html code in a controller return as well. Should it be more like:
controller checks if you are following someone
the controller passes a boolean to the view
the view calls the helper with this value to draw the appropriate button
Also, as a secondary question, I have been doing a fair bit of looping through mysql arrays in foreach loops to process mysql results returned from the view. It seems like my views are getting somewhat complicated, but I can't think of another way to do it, although perhaps this should be done in another helper as well?
Apologies if this is a naive or repetitive question, there is indeed a lot of discussion surrounding this subject but it is not always easily relatable to another project.
Helpers are certainly one way to modularize anything that isn't DRY. Another is to use Partial Views. CodeIgniter looks like it supports partial views. Here's a good breakdown - not PHP specific but the discussion should be agnostic.
As far as handling user logins is concerned, you will probably want to use a static class and the singleton design pattern, which will allow you to check to see if a particular user is logged in or not anywhere in your application. There is a good tutorial here
http://www.phpandstuff.com/articles/codeigniter-doctrine-scratch-day-4-user-login
Loading the helper, I don't believe loading it in your controller will automatically load it in your view. I think you have to re load the helper in your view file, or you have to autoload the helper. (cant remember off top of head but Im pretty sure).
Regarding looping through the mysql results, you should be using a model for this, always. Any functions which are grabbing or sorting information from your applicaiton, should be done within the model. Then, in your view file you loop through the results and format the data how you choose to.
When developing http://newspapair.com which has the vote functionality you mentioned I used helpers and custom classes to spread the functionality across multiple views.
Helper - has functions without a class. So a standalone function or group of functions can be placed in a file and saved as a helper.
For instance I used a helper with generic form processing functions for NewsPapair, instead of a static class. But this is not the "best practices" thing to do. I did it this way because I already had the functions from a previous project.
As far a looping through MySQL results, try to write a query that allows the DB Server to do the heavy lifting. This will make your code more efficient. Perhaps ask a question about a specific query with example code. Plus do all of the data gathering in your Model.

How to integrate AJAX into a MVC-style web application?

I'm developing a web application using a very simple (maybe not really MVC-compliant) MVC framework, coded by myself while developing the application to keep the code clean.
My application, though, has many AJAX components and now I'm stuck trying to integrate them within the general MVC structure. How should they be integrated?
I have something like this in my Javascript files:
$('#pageList').load(BASE_SITE_URL + 'ajax/pageList.php');
and pageList.php used to have a structure like the following one:
<?php
require '../includes/config.inc.php';
require BASE_PATH . 'includes/init.inc.php';
// a whole load of Controller logic here and then...
echo "<table>";
//display some user data
echo "</table>";
I'm really confused about this, any advice is appreciated
Few pointers - your website should be functional without javascript. For example, if you have pagination with page urls like /list/?page=1 ... /list/?page=n then you should make sure all of your pages are clickable without actually needing javascript.
Javascript should really be an extension to your website. In the above example, you can come back and use js to replace the functionality of all the pagination with a simple ajax behavior. What you would probably want to do is use jquery.load to do something like:
$("div.content").load("/list/?page=2 div.content > *");
Note the selector after the load. This is very important because I haven't actually created any new HTML pages to make my website AJAX enabled. Instead I use what already is available to the browser as a simple URL and load it using ajax.
Of course, there are times that you need AJAX only content where won't really exist on a URL. In a situation like this I recommend creating a controller for all your ajax stuff and then rendered each path with a view.
I hope this helps.
Here's what I do in my apps:
check for a $_SERVER variable called XMLHttpRequest. If it's set, it's an ajax request and then you can do some logic so that your code doesn't load the views (templates and what not) and outputs a different header() (if any)..
I usually have a js script related to each view called update.js. It's role is to define how the user interacts with the view and create the HTTPREQUEST.
Then I have a file called controller.js that receives it, decides what to do with this request
and asks the model for the response.
Finally the update.js which belongs to the view updates the view with the new information received from the model.
My app directory structure is like this:
model/
model.class.php
business.php
controller/
controller.php
controller.js
view/
view.php
update.js
index.php
I organize the files by it's role rather than the type. I think this is the best approach to the MVC pattern with AJAX. Remember that the aim of this pattern is to keep encapsulation and scalability and this is the best way to do it for me.

How can i handle a form submit using REAL OOP in PHP

Im used to java and creating UML.. and i was wondering how can PHP be OOP, the objects live only until you make a request.. then they destroy, so if im using a database is useless to create a class and add the members (variables) to the class, they will be useless.. i cant pass the main system object from one page to another, or similar so how can PHP be compare to jave? you never do OOP .. i mean REAL OOP.. not creating classes , in fact your index will be a procedural file with some object instance and then ? how about if i make a html form and i want to submit the data.. i have to call a file which is not a class is a php procedural file were i grab the submited data with POST, from that file you will instance a class and do some logic there.. but for me thats not pure OOP.. can somebody point me to the right way of OOP using a form submit example ?
Thanks!
You're labouring under a misapprehension that object oriented programming by definition includes a persistent environment with objects that exist independantly of page requests. I'm afraid it doesn't.
PHP does do "real" object-oriented programming. But PHP's execution environment is like executing a CGI program: upon a page request, the program starts and it ends when the page is finished. Within that paradigm, objects can exist only as long as the page is producing content. Therefore, the first thing the page must do is to load the framework to define and instantiate the required objects, such as a database handler and object mappers that must load and save their data within a page request cycle. Some frameworks will also create objects with the page-request data that your code and objects can then access, sometimes from within objects.
But PHP does not provide this natively because it does not enforce a framework. It is by nature procedural so a framework must be added so as to define and create the desired objects if you don't want to work that way.
There is an advantage to doing things this way. It means a page's code need only concern itself with a single page request. Almost all issues to do with data-sharing and multiply-threaded execution is pushed out to things that can handle it invisibly, like the database and the web server.
Check out any of the latest php framework and how they handle forms. (like ZF or Yii).
b.t.w the "problem" you refer too is client-server architecture and not a minus of PHP.
Each request is a new process with a new MAIN or new Class with static main function which are practically the same.
"so if im using a database is useless
to create a class and add the members
(variables) to the class, they will be
useless"
It sounds like you want an object-relational mapper. There are several popular ones for PHP, as discussed at this previous question.

Kohana - where do you put AJAX scripts?

I am using Kohana but this question applies to Rails, CI, or any other MVC web development framework. Where is the best place to stick one's server side AJAX scripts?
I was planning on creating an Ajax_Controller and using a method/action per individual script.
For example, a login form on the home page index.php/home would send an XMLHttpRequest to index.php/ajax/login, and the edit profile form index.php/profile/edit would send an XMLHttpRequest to index.php/ajax/editprofile. What's the best practice?
I tend to put my ajax actions in the same controller as the non-ajax actions for any given model.
When I can, I try to use the same actions and only change the output type. Most tasks should have a non-ajax version anyway, so this tends to work quite well. Very handy for reducing logic duplication.
AJAX crosses all of the MVC boundaries. That is, it doesn't go into just one of model, view or controller.
Your AJAX scripts will be calling scripts on your site - so this would involve a section of your controller layer which you've created for the purpose.
That controller in turn would access the database using the interface provided by your model layer, just as a non-AJAX request would.
The data for the response back to the client may be packaged as JSON or XML or something. Technically this is the task of your view layer, though if your application's definition of a view layer is nothing more than "an HTML templating system" rather than "processing and formatting anything that gets sent back to the client whether it's HTML or something else like XML" then your XML or JSON generation may need to go into a new little section of its own.
As for sending the scripts (Javascript files) themselves, this is probably going to be handled directly by the web server rather than from within your MVC framework.
Do you make different controllers for GET and POST requests? I don't. In my opinion, JS requests shouldn't be dealt with differently either.
I personally see JS requests just like GET, POST or any other type of request. So if I have user-related JS-based actions, I simply create them in the user controller.
If you mean the AJAX (Javascript) scripts themselves, these should go into your public/js folder. However, if you mean the actions invoked by these AJAX requests, they should be treated as any other actions of the respective controllers. To be completely RESTful, you should be using a different format (json, xml, etc.) as return values for those actions.
I am a noob, but based on my understanding, to achieve ajax with php mvc... thinking steps might be:
change the definition/function of the existing php view layer from 'HTML template' into 'results formatting (XML,JSON etc..' -> results from relevant module, which then called by controller to output into AJAX object, then it means you need to write view layers into each particular class with formatting methods
PHP module layer stays same
build a Ajax router class with JS which stay the same structure which you route in your PHP
build a ajax results handler class with JS to handle the results got back from PHP controllers (XML JSON etc..), then from here do whatever user interactions you want, this will be called by above Ajax router class
So,
ajax router (send XMLhttprequest)
-> PHP controllers C
-> PHP module -> PHP view results M
-> PHP controllers output results V
-> ajax results handle (into page)
I don't use Kohana but what I do in my framework is that AJAX scripts are controllers. I try to treat them as standalone controllers but in the end they are just controllers.
Using a separate controller is a good idea. I either organize my controllers by function and then actions by return type.
Additionally, when I'm using Pylons I can decorate an action with #jsonify and that will automatically take care of converting python objects to JSON. Very handy.
I like to keep all my ajax requests in one controller, typically dispatching their requests through a shared model (that the non ajax controller also uses)
The main difference being the view that results via the ajax controller (html fragments, json data, etc) or the non-ajax controller (full pages)
You could wrap it up as a general REST-api, and use RESTful conventions and URIs.
Example:
Instead of index.php/ajax/editprofile it could be a PUT request to index.php/api/profile/profilename.

Categories