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.
Related
I'm working on several reports for a web application. I have to show some data from my database in some bar/line charts. I'm using Codeigniter framework so my backend is PHP and my frontend is mostly composed of html and JS. As for displaying graphs I'm using e-charts library.
My question is, what's the best practice when retrieving data for the charts. I could use an ajax call and retrieve general data, then format it in the frontend using JS and finally drawing the chart.
A second option would be to also make an ajax call, but making an endpoint that already sends the data in an specific format that the graph can understand. Then that endpoint would only be used by this specific graph.
A third option is again making a specific function to retrieve and format the data in the backend, but this time work with both the html and the data in the codeigniter view. Then serve the html+js page with all the data required, no asynchronous call involved.
All three options have some limitations, so I'm wondering which is the best practice. And if you have another option I'd like to read about it.
I guess it depends on your needs. Overall, I think the best practice is to make as few dependencies as possible between your backend and your frontend. Especially if you plan to change your frontend or want to serve multiple frontends.
So the endpoint should return data in a format that can be understood and used by everyone.
You need to inject services into the controller of this API. So the controller receives data from the services and responds to it. Just that. The data extraction (from the database) and processing must be done by the services.
This way you are more flexible. You can create an API controller for your AJAX calls and another controller that renders HTML if needed.
With the first one, the API controller, as I said above, the controller receives data and returns it. You let the frontend take care of the computation, transformation, etc.
With the second, the controller has to get the data from the injected services but also compute, transform, etc, then render HTML.
Read about the single-responsability principle or, more generally, the separation of concerns principle.
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!
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.
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.
I am about to begin a web application. Before I begin, I would like to get some advice as to what the best work flow/order is for creating a web application such as this.
My project will consist of a server-side with PHP and MySQL. The client-side will be XHtml, CSS and jQuery. There will also be AJAX used.
I'm sure that it can depend on certain situations, but, overall, what is the best order for developing a project with these credentials?
Should I start developing the server-side first? Or should I begin with the client-side? Or should I do both at the same time? What about the database - should that be a first priority? Then perhaps the DAOs?
Start with the data first. The server-side data is the persistent, essential core of the application. If this data model isn't right, you have nothing.
You should be able to unit test the data model to prove that you have the right attributes and relationships. This doesn't require much. A few test cases to insert, update and query.
You will support that data model with back-end processing.
This, too, should be unit tested to demonstrate that it works and does all the right things to your data model. This will be a bit more complex, since this processing is the application.
Then you can think about the data model as exposed by web services to Ajax.
This, also, is testable to prove that the JSON does the right things. This testing is often fairly complex because this is what the GUI front-end relies on. This has to be right.
Then, once you have that Ajax data model worked out, you can write the front-end GUI.
The workflow you're describing is what I use for my own (solo) projects.
I like to meet in the middle. I do data modeling first, and simultaneously start prototyping the interface. Business rules come last and pull everything together.
I also find it "inspiring" when I have a GUI to look at... it encourages me to make it do something. Furthermore, GUI's tend to undergo the most revising, so starting them early in the process ensures you'll be happy with the finished product, and that it'll be finalized by the time your business logic is implemented.
If I'm working for a big company that's not sure of exactly what they want, I'll start with the UI first. This way they get to figure out what they want before I've put a lot of time into the rest of the system.
On the other hand, if I know exactly what is needed, then I will start with one feature and work my way up through the layers, database, controller, view, and ajax, until that feature is done, and then go on to the next feature. This way I've got less context to remember, and the client always has something new to play with.
I can't tell you what's absolutely best, but what works for me is...
Talk to the business people to get an idea of what they want.
Draw the UI with pen and paper. Boxes represent pages. Buttons and links have arrows pointing to other pages. Don't need every microscopic detail. Some things are implicit.
Once the UI is mapped out pretty well, design the DB schema. Sometimes I'll write out all the tables in a text file like this...
pets
----
id
name
species
# etc...
Then implement the database. I use Rails migrations. You might write the DDL manually.
If you have models or DAOs or something along those lines I would implement those next, with unit tests.
Then I usually work through the app entity by entity. Get the view and controllers working. Rapidly switching between the testing code and the implementation code.
That's the general sequence, but the whole time there are adjustments and so on. You'll need to go back to your DB design and evolve that as you build the actual functionality.