design structure of json, ajax, php and mySQL - php

I have a new project coming up, and I would like to use ajax to get the mysql result (in json format) so that I can use jQuery ajax to display it properly. Since I'm really new to json, ajax, jquery please tell me if my design structure is okay or not and if there is any security issue.
Here is my design:
Core.class.php - it will use the PDO object to connect to the mySQL database, and it will do some queries and return the results
json.php - it will create a singleton core obj and return the result in json format, based on the querystring data. ie.
if ($_GET['get_type'] == 'employeeinfo')
{
return get_all_employee_info(); // and in this function I'll use the core to do query and echo all employee data in json format
}
else if ($_GET['get_type'] == 'companyinfo')
{
return get_all_company_info(); // and in this function I'll use the core to do query and echo all company data in json format
}
...
index.php - it will use:
$.ajax ( {
url: 'json.php',
data: //getdata type,
success: function(results) { //use results to populate data and display on this page }
});
to load data and display in result HTML format.
Also, user will have to login first in order to load index.php, and once logged in successfully, session will be created.
So in index.php and json.php, I'm going to check the session, if failed, will throw the die() method.
so is my design structure okay? is there any security issue?

Here are some tips:
Don't return your database objects directly using json, as this would potentially expose your database structure. Simplify your data before return it (don't return more data then you need)
Use a JS template engine for rendering the data. Some examples:
https://github.com/justjohn/twig.js/wiki
http://twitter.github.io/hogan.js/

Check out this tutorial on creating your own simple framework. I found it very useful when creating the basic structure for one of my projects. Every step is explained in detail, so that it is (at least in my opinion) easy to understand for people who are new to PHP.
It explains how to create a basic structure for your project that has a single entry point for your application. This means that each URL you call in your browser will initially start the same php file. Based on the URL, different PHP classes (Controllers) will be started and render the content that is needed. This has many advantages, for example you will need to check only once that a user is logged in.
The tutorial focuses completely on the server-side structure, so it does not cover any AJAX or jQuery concepts. The Symfony components however make the implementation of AJAX-based calls a piece of cake.
If your project is not really huge, I recommend trying RedBean for the connection and manipulation to the database. It makes it really easy to retrieve, store and create new database tables or entries.
In case you are interested I can give you some tips on how to implement user and session management.
Good luck!

I'm not sure how big is your project and how much effort you are willing to pt on this aspect of it. But if your project is big enough you would want to look into some JSON server like Zend's. It can help you architecture your project much more reliable. It's pretty simple to work with and you can find several examples for it on the web.

Use an existing framework. It's better to learn couple of frameworks or three before you write your own. http://davss.com/tech/php-rest-api-frameworks/ gives you an example of rest frameworks many of which are very lightweight but would provide you with routing, autoloading, concern separation strategy and many more.
As mentioned above map your data into a data structure that makes sense instead of just exposing your database structure. This will give you more control and flexibility. Could be a simple array or a class that you map your database object onto and then to json.
A good and simple framework will guide you through and will enforce good practice.
Good luck!

Related

Ajax (client) vs PHP (server), Loading DB Data

I am embarking on part of a project now that has me planning on how to load a dynamic table data from a DB. I have uncovered two basic methods.
I believe that I can use url query strings to communicate with the php backend of my phpbb3 forum. And it can load the appropriate data and ship it off to the user in full static page chunks. So I would have something like /stats.php?page=3&orderby=name&dir=desc.
Or I can just send the same empty page to everyone and the browser can dynamically load anything that the user wants using ajax.
Or some combination of the two.
What is best practice? What are the downsides and upsides of both?
It really depends what you're trying to do. For simplicity's sake, I would say that the first option (just load it with the appropriate query string variables in the URL) is better.
Rendering a page using AJAX is pretty much always more complicated. However, it also gives you much more control over the UI if you know what you're doing. From my experience, if you want your page to be more like a "web app" with dynamic things happening everywhere, it is much easier to simply load JSON data from the server via AJAX and to dynamically create views via some sort of templating system. Otherwise you're stuck with loading the DOM with PHP, and then somehow communicating that data to your JavaScript, either by using data-XXX attributes on DOM elements, having PHP output a JSON string at the top of a page and assign it to a JavaScript variable, etc. It could get very complicated and convoluted.
In your case it looks like you're just trying to allow users to view certain data from your forum. Barring any additional requirements, I would recommend going with the first option because it will be much easier. This is simple enough that you don't seem to need to load anything dynamically.
A good rule of thumb is the more complicated and dynamic your UI, the more you should think about moving to a "web app" framework, and just let the server act as a REST server.

how do i map from *sql to php to javascript and back?

I write *sql / php applications a lot a I find myself having to rewrite javascript all the time to do the same stuff over and over. Usually, when the API i have to work with is very simple, its not a big deal to write one-off ajax methods to interact with PHP, which updates sql tables via PDO.
But, when it comes to big data objects sent from php to javascript that need to be parsed, edited, updated, sent back to PHP, and then updated by an application layer, I'm writing javascript all day long to handle these "big objects" and every. little. thing. that could be updated within them.
There has to be a better way. What is it?
What's the nature of the changes that cause you to rewrite large swaths of your frontend js code? Is it new data that you need to surface in the frontend, or is it changes to the structure of the data?
If it's new data and you want to stop focusing on updating your frontend code to deal with it, you would probably need to implement something that lets the javascript build out your frontend in a more dynamic way. I could see this working as a service that passed back as a structured UI mapping in some data format that your frontend js could parse (you'd have to include all the data you needed and probably some information about the format of that data, ie, string, text, date, etc).
That might work alright for some form data, that's basically how form objects work in MVC frameworks like CakePHP or even Drupal. And in fact if that's your goal, to just provide some user-facing content entry, you might even be well-off to check out implementing this code in one of those frameworks.
If the problem is that you're making changes to your structural data, but by and large you're surfacing the same data fields, you probably just need an abstraction of your front-end data models and your backend data models. You can come up with your javascript object definitions that define what the structured data you pass back should look like, define what your backend model looks like, and then define a mapping layer between the two. If the structure of the data changes in the backend, your contract between the javascript object definition and the mapping layer wouldn't need to change, and you could merely change the contract between the mapping layer and your backend data model layer.

Ajax loading for complex projects

My problem is actually not the ajax loading itself, more the capability to load it without javascript. I mean, I cope easily when I code my whole project just based on ajax-availability OR just without the use of ajax.
//EDIT: Although Arend already had a more or less valid answer, at the same time 'there is no direct answer to this question'. However, I'd like to see some other approaches of developers for scenarios like mine though! Even just a few links can help!
Basically I just get frustrated, coding everything twice on the same page to make sure that both users without and with Javascript enabled have the same experience. It's annoying and I was always wondering how others solve this problem.
When I update for example two divs with dependency on the same variables, it gets messy. Here's an example:
non-js-version
require 'classobject.class.php';
$another_var = 'something';
$class = new classobject($_POST['variable']); // just an example to show that this is dynamic - I'm aware of injection!
$function = $class->returnsth(); // returns 1
if(isset($_POST)) {
echo '<div id="one">Module 1 says:'; $require 'module_one.php'; echo '</div>';
echo '<br /><br />';
echo '<div id="two">Module 2 says:'; $require 'module_two.php'; echo '</div>';
}
Now in module_two.php and module_two.php I have code that executes differently depending on the return variable of $function.
Like:
if($function >= 1 && another_var != 'something') {
// do stuff
}
else {
// do other stuff
}
Now as this works easily with a reload, when I want to load the two modules on keyUp/enter/submit or whatever, I have basically a few problems:
I have to send the $_POST variables manually to the modules to use them
I have to re-execute the class & it's methods and make a link (require_once) to them in each of the module-files.
As $another_var is not existent in the modules, I'd have to send this variable to each modules, too (with post for example) and then before it can be used, I'd have to 'change' it like $another_var = $_POST['another_var'];
I find this mildly annoying and I wonder how you guys do that. I hope my way of coding is not too silly, but I can't think of another way. It's probably hard to relate to my very basic example, but to bring a whole project with the code would be too much. To sum it up, I'm looking for a better way to code and clean this mess up - there must be a way! I thought about sessions, but for compatability I don't want to rely on them either (if someone doesn't allow cookies).
In case you can't relate to what I'm trying to accomplish with that way of having my code assembled, I'll explain a scenario I'm facing quite a lot (not important if you already understand my misery):
Basically I have my index.php page where everything gets executed, with the html body and css styling and so on. This page expects some variables, that get set from the page that requires the index (like $another_var in my example).
Now other variables can get set too (from a form for example). Depending on that different classes and methods load new variables (arrays) that get used in while-loops in my modules to echo everything out.
Hope that's not too abstract. Think of a booking system where some variables are set from the page you are coming from (the event you want to book) and then a few more things get set by the user (a timespan, some preferences,...). In the end it's supposed to show results from the database all the way to the end-result - you can say the user narrows the results from step to step.
There is no direct answer to your question, but there is some food for thought.
Seperation of concerns
You can think about if you can perhaps seperate your buisness logic and layout logic. Often the use of a template engine can help greatly with that. I've had positive experiences with for example Twig or Smarty (was some time ago, not sure how they measure up right now). It requires you to write your code in a (less linear) way, but more logical.
A typical example of an OOP like seperation of concerns might be something like this:
$this->setParam('Myparam','myvalue');
if ($this->isAjax())
{
$this->setTemplate('ajax.php');
$this->setLayout(false);
} else {
$this->setTemplate('normal.php');
$this->setLayout('Mylayout');
}
return $this->render();
It is an imaginative situation, which can be found in many MVC like applications and frameworks. The main idea is that you should have the possibility to seperate your layout from your data. I would suggest looking at some of the modern frameworks for inspiration (like symfony, codeigniter, zend framework).
Glossary / Often applied concepts in a decoupled PHP application
Here is a quick list of concepts that can be used.
Example mvc in php: http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
Note: I don't really like the implementation. I much more prefer the existing frameworks. I do like the explanation in total of this tutorial. E.g. for me this link is for learning, not for implementing.
Silex
For a simple decoupled php micro-framework I would really recommend silex, by the makes of symfony2. It's easy to implement, and to learn, but contains mainy of the concepts described here; and uses all the php 5.3+ goodies such as namespacing and closures.
see: http://silex.sensiolabs.org/
Frontcontroller Pattern
Only have one, and one only point of entry for your code. I usually only have one, and one only point in your application. Usually a frontcontroller 'dispatches' the request to the rest of the application
http://en.wikipedia.org/wiki/Front_Controller_pattern
Routing
A routing system is often used in combination with the frontcontroller pattern. It basically describes which URL is connected to which module / controller. This allows you to change the way people access your app without changing the urls.
See: https://stackoverflow.com/questions/115629/simplest-php-routing-framework
Controller
A controller is the place where buisness logic is applied. Getting the data from the database, checking privileges, setting the template, setting the layout, etc. (although this is also moved outside the controller if it becomes too big of a seperate concern).
Model
The model basically is the layer in which use manage your database. This can be a simple class where you move all your mysql_* functions, or it can be a full-featured ORM. The main philosphy is that all the logic related to fetching and placing information in the database is seperated.
One step up: ORM
An often used method in applications are Object Relational Models, these 'map' SQL records to PHP objects. Doctrine and Propel are two of these well worked out libraries. I heavily rely on these systems in my development. In this sense, the doctrine or propel part will represent the model layer.
Doctrine: http://www.doctrine-project.org/
Propel: http://www.propelorm.org/
Other ORMS: Good PHP ORM Library?
PHP ORMs: Doctrine vs. Propel
View:
The view usually consists of a templating engine. Some use plain PHP as a template, others, such as symfony create a seperate scope in which variables are placed. There are many discussions and opinions about what is best, one is right here on stackoverflow:
Why should I use templating system in PHP?
PHP vs template engine
Ones I like:
- Twig: http://twig.sensiolabs.org/
- sfTemplate: http://components.symfony-project.org/templating/
- Smarty: http://components.symfony-project.org/templating/
Decoupling mechanisms:
Event based systems
Using events in your can help to seperate the code. For example if you want to send an email after a record has been saved, events are a good solution to do that; in general the model should not have to know about email. Thus events are a way to connect them: you can let your -email-send-class listen to certain records in order for them to send the right email. (Perhaps you'd rather want your e-mails send from your controller, this is probably a matter of taste).
Dependency injection
When using OOP code in PHP many relied on having singleton classes running around (configuration, etc). From an OOP point of view, this can be considered bad, because it's hard to test it, and it's not considered very elegant to have dependencies running around like that. Dependency Injection is a pattern that came form Java and is now used in the newer frameworks to get around this. It might be a bit difficult to wrap your head around, but you will see it coming back in several new frameworks.
Dependency injection in php: Dependency Injection in PHP 5.3
Frameworks:
A lot of these methods are difficult, or a lot of work to implement yourself. Many will reside to a framework for this. You may or may not need a framework. You may, or may not want to you a framework, it's your choice. But it's still useful to learn how the frameworks do it, and not try to reinvent the wheel yourself.
The no-framework php frameworks: https://stackoverflow.com/questions/694929/whats-your-no-framework-php-framework
Good habits: https://stackoverflow.com/questions/694246/how-is-php-done-the-right-way
Frameworks worth looking at (imho): CodeIgniter, Kahona, CakePHP, Symfony (1.4/2.0), Silex, Zend Franework, Yii. There are many many more, each with their dedicated fans and haters.
I wrote something like this with PHP. I already had abstracted the rendering of every page such that I define a $content variable and then require('layout.php'). The $content variable is just a big HTML string.
I wrote a PHP function to determine if request was AJAX or not.
The non-AJAX responses render the layout with $content in the middle, b/t header and footer layout content.
AJAX requests basically get this: json_encode(Array("content"=>$content)). And I use jQuery to get the HTML out of the JSON response and modify the DOM. Using json_encode() will handle escaping the string for javascript.
In the end, I effectively have AJAXified every page w/o over-engineering a complex solution.
Any browser that supports AJAX can also open a link in a new tab/window to simulate the non-AJAX request. (Or bookmark/share a link, too.)

Suggestions on making a PHP / Javascript / MySQL framework?

I have been thinking about this problem for a while now and haven't been able to conceptualize the best way to do it despite much thinking and many attempts. I need to know best practices for how the data-flow of an interactive web application can be best organized, in terms of database, server-side code, and client-side code. The languages I am working with now are MySQL for the database, PHP for the server side language, and JavaScript/CSS/HTML/jQuery for client-side code. I am trying to find a clever way to let the user safely do things like select, update, delete, and insert from the database, and have it display in a pretty format in a web page.
I am already very good at making great looking interactive websites, writing awesome PHP applications, and setting up organized and efficient database schemas. However I have been struggling at finding an abstract and efficient methodology that connects them all together. I am not looking to use an existing framework. That is simply not an option for me. I am the type of person that needs to understand the way things work and what they do. I would however, look at an existing framework for pointers, but all of them that I've look at so far have mostly just confused me.
Here are some things to consider about my framework:
The PHP code returns data from the MySQL server and back to the client-side in JSON format. For example, a query to the database for Martin Scorsese movies might return something like:
{ totalRecords: 2, records: [{ title: 'The Departed', year: '2006' }, { title: 'Goodfellas', year: '1990' }] }
The client side receives and parses this.
For invalid calls to the database, such as an invalid login, would it be better to return a valid HTTP response with "false" (thus invoking a success callback), or return an invalid HTTP error message (thus invoking a failure callback).
I am unsure how to set up the PHP. Should I make one function for each type of mysql operation (e.g. "SELECT", "UPDATE", "DELETE", and "INSERT") ? Should it just be a functions library or all contained in a class? Would for some reason there need to be multiple classes or some sort of class hierarchy? What are some good practices of data access?
I have been using jQuery's ajax function to make calls from the client-side to the server-side to retrieve a JSON string and then parse it. The success callback function is invoked on a successful call, which is what receives the JSON formatted string. From here I pretty much don't know what to do. I was thinking of sending the returned JSON string into a function of some sort that would parse the JSON and return something like a HTML formatted table to display the results. However, I would not be sure how to set up the class hierarchy.
My boss at work was telling me about a hierarchy that looks something like this:
However, I am not completely sure why so many pieces are needed such as the Data-Connector, Adapter, Manager/Provider, Controller, and View. I am sure I will need some of them but not all and I am also not sure what the best way would be to set up the class structure. Note that I am somewhat new to a MVC approach.
The code needs to be as abstract and re-usable as possible! Currently I have a ton of spaghetti code and it makes me cry on the inside :'-(
So uh... this is where I am at currently. Any help would be greatly appreciated as I feel like I am a lost puppy not getting it and that any code I write quickly is becoming sloppy and not-usable or maintainable. If you could provide any insight to your own framework that you use, or take the time to read my long post and evaluate my own, any input to make me think about it in a different way would be highly appreciated. :-)
Read this book: http://martinfowler.com/books.html#eaa or something comparable about design patterns. Consider revisiting existing open source frameworks and ask questions. I know from personal experience that coding before research and design on complex projects is a waste. Even if you don't produce anything from this you will have learned something useful.
I understand that your objective is to make your own framework, but still I would like to suggest that before you start you should study all current major platforms to a level where you really understand how they work and why certain design decisions have been made. Each design option has it's pro's and con's and designing a framework is a fine art of making the right compromises.

Outputting data with JQuery & PHP

I have a general question regarding quality of writing code ...
I'm working on website, that outputs data from MySQL with PHP and it is being called with $.get() / $.ajax() with jQuery....
Now my question is .. the data I´m exporting for example: an array of comments (from class Comments) for a specific post, and this array is being returned from PHP as a string with its HTML manipulation (return '<div id="this->$data"> this->$data</div>';) and with the JQuery manipulation, I´m adding all the comments as list elements or anything else to a specific html element.
Is it useful to do this? Or it is better to send the array in a variable to jQuery, and then work with its elements and make the dynamic html code directly in JavaScript/jQuery..
If that was confusing, is it better to generate the html code in PHP when returning /echoing, or to generate the html code in jQuery after receiving the core data from the php?
I know there are other methods like XML JSPN, I'm just asking here about the efficient with generating HTML to manipulate core data (example: Array or Core Json data)
Let me elaborate on AlberVo's answer
The PHP file which is generating the data, if it is going to be called from possibly other sources, say from an iPhone app, or a command line application or a desktop application, or even if say 2 months down the line you think your website's front-end is going to be say Flash based, then its better to keep your PHP code front-end agnostic and just return xml/json/yaml.
If you know its going to remain a HTML/Javascript based front-end and front-end load speed is an issue, then you can do all the hard work of converting your data into HTML in the PHP file.
In the end personally, I'd say stick to just generating front-end agnostic xml/json/yaml. You never know what direction of the code the future may bring. And architecting your design this way keeps you flexible a.k.a your front-end and middle-tier are loosely coupled.
A few more advantages to such an approach (which really just arise from the loose coupling)
Work organization. If in the future someone else is also working on this project one of you can work on the middle-ware and the other on the front-end as long as you respect the json/xml/yaml in between. Your work is not going to affect the other's.
Testing. Using a xml/json/yaml also allows you to unit tests your PHP code and front-end easier. Your test data is just xml/json/yaml.
The way I decide on this is if I foresee using the data for things other than that specific use, then it is better to return the raw data such as json or xml.
You will want to consider which part of your application should control your page structure and layout. Do you want your page structure to be defined by the PHP script that just returns data? Or do you want to define the page structure in the page itself, and let the PHP script just return the data as needed.
This is an issue addressed by the MVC (Model-View-Controller) pattern. If you follow the MVC pattern, you will separate logic from presentation, rather than mixing the two. This allows your application to remain as flexible as possible, and also promotes code reuse.

Categories