I want to refactor my php site which supports a front end which makes ajax calls.
Currently my ajax calls a php page which stores all my backend code and based on the parameters passed from the ajaxcall it determines which php methods to run.
I realize building a rest API as the php backend woudl be better but was wondering if there is another alternative? ie a good way to structure a php page that allows for clean re-usable ajax calls from the front end?
Thanks
There are multiple ways of doing such kind of web development. It could be REST based micro framework approach in PHP where you invoke different views. Another could be to invoke the PHP code solely based on the input or interactions on the view (HTML/Javascript) using AJAX. Depends what you want to achieve.
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 am not sure, what is conceptionally thought the right way to serve data from an php mvc backend to the frontend.
Basically, I was happy with the things in angularjs: Put some controllers into DOM and some directives for events like clicking, if conditions etc.. However, times have changed and we have to move on.
So here is my question: I have an huge PHP MVC backend with an template engine. And I would like to keep the things in place, because serving only json to the frontend would completely remove the View out of MVC.
Maybe serving some inner views as json would be ok. But I need the HTML structure to be served and prerendered by PHP. So mixed syntax with php template engine and angular. Let's take the example on angular or vue2 with TypeScript (that is what I prefer to use in my apps).
How to do this correctly to stay future-save? I mean this component style is nice, but I need to get it combined with my backend in smooth way. If I would just give an templateUrl, how could I make sure to use the full advantage of caching technologies and stuff like that from the frontend?
Creating hybrid angular apps is a bit tricky because if handling state is tricky by itself in angular, try combining that with the state in php.
The best way I've found is to think of angular as a widget library.
By creating widgets (components) that contain do the heavy lifting UI wise you can come a long way.
I wouldn't try combining angular components templates with php, but instead pass data into the angular components. That way you can easily test the angular components and you will be able to reason about what is in angular land, and what is in hybrid land.
If you are debugging an angular component, you know it by checking the data coming into the component if the bug is in typescript or php.
A couple of scenarios.
Form validation
You have a form that angular handles validation on, but then submit it using the normal <form action="/submitform" method="post">
Advanced form
You have a more complex form possibly with multiple views where you handle post the data via a json api and angulars Http service.
Graphs
Presenting data graphically via a graph widget.
Howto
Make your whole php app an angular app but don't use angular's routing.
inject php state into components via #Input()
<my-component showinfo="<?= $showInfo ?>"></my-component>
By passing in all php variables via inputs you will be able to test the angular components easily via jasmine.
angular-cli
I would probably use angular-cli to create the app. The problem there is that it defaults to use webpack dev server which only runs in memory.
Instead use
--watch so that angular rebuilds when files change
--output-hashing=none so that angular always outputs the same filenames so that you can include them in your app
--output-path= to specify where you want the build files
ng build --watch --output-hashing=none --output-path=my/php/public/folder
I have a PHP class/object which acts as the primary data source for my webpage. I'm using jQuery/Javascript to provide a dynamic interactive experience for the user. Both parts work independently really well.
I'm now trying to find an elegant and clean way for the javascript library I've written to access and update data stored in the PHP object.
Communication Javascript -> PHP: I've previously always created a PHP wrapper that takes input over the GET/POST and routes the data to the appropriate PHP function. This works well enough but surely there is a cleaner way to interface from javascript to PHP?
Communicating PHP -> Javascript: Previous websites I've written have seen communication from javascript to PHP only. The PHP would output HTML which Javascript would place in a container (Standard javascript usage I guess). However, in this website, the Javascript library I've written requires structured data in return which it processes to perform multiple UI updates. It seems that looking into JSON would be the right thing here but there seem to be a variety of options.
I would love the advice on the best way to get your PHP and Javascript communicating in both directions is a clean and elegant way.
Thanks!
I am going to start developing a webapp using php framework codeigniter. The app is going to do most of the database dealing using ajax/jquery. From what I know, I would be implementing the following steps to do a particular task
Create a view page
The events performed on view page's elements, i.e., click, mouseover etc. will be attached to event handler functions in js files included in the view
js functions will be making get, post requests to server side
In case some dynamic values need to be passed to js functions they'll passed using inline php code given below.
On server side, some database queries will be performed to generate a json(sometimes xml) which will be sent as response
Based on the response, the js function callback will manipulate the dom.
Now, my question is whether there is an ajax framework that can further simplify the implementation of steps given above. if not a framework, then may be a better approach to implementing ajax and php.
// This is part of view page
<a href="Delete User" onclick="deleteUser('<?php echo $userid; ?>')" />
Welcome to jQuery. This is not an AJAX framework (I have never heard of one of those) but it is a JavaScript Framework that incorporates some easy AJAX functionality.
Everyone talks about "integrating with the PHP framework!" like its some sort of crazy feature in PHP. JavaScript makes a request to a URL and does something with the response. That URL could be native PHP, CodeIgniter, a static file or bloody ColdFusion, it is all the same.
So if you are using CodeIgniter, in your view put:
$.get('/controller/method/param1/param2', function(data) {
$('div#someid').text(data.whatever);
}, 'json');
I don't really know what you mean by "AJAX framework" and whether you're talking about a clientside or serverside framework.
In the event you're looking for a clientside framework that handles client-server data synchronization, check out http://documentcloud.github.com/backbone/
Codeigniter has a javascript class that might help avoid "the Mess" you spoke of.
http://codeigniter.com/user_guide/libraries/javascript.html
I am a PHP and ExtJS user. I am looking into developing an application using a good PHP framework (CakePHP; good as in "I consider this good for me") and ExtJS version 3. What I would like to achieve is a complete Ext viewport with many grids and functions that would call PHP urls for retrieving data, saving data, edit/remove data (not just for grids, also for treepanel and such). I would like to use CakePHP as backend with all its capabilities for executing these functions. My first goal is to integrate the obAuth component (or any other secure authentification plugin for CakePHP) with an ExtJS 3 login interface. I am searching for the best method of combining these too so that I can easily restrict functions based on the usergroup access. I am thinking of a setup where the logged in user makes one post from Ext regarding the execution of a function and the CakePHP response made present as errors or notifiers through Ext alert boxes.
Do you think this is possible ? Any thoughts of an ideal config for this ?
Thank you.
If you're going back and forth between JavaScript and Cake a lot the first thing you might want to do is override or extend the default View class so it'll package variables you set in the controller automatically into a JSON array or whatever you prefer. That'll save you from having to make a view for each action and/or overriding the layout each time. Study cake/libs/view/view.php and/or cake/libs/view/media.php, you can create custom views in app/views/.
Make use of the RequestHandler Component a lot to reuse logic both for normal views and AJAX.
Beyond that it's normal JS with a PHP backend.
This is actually very easy. First, integrate the obAuth Component into a basic CakePHP install, to see if it works properly and doesn't have any strange quirks. Once that's done, get to work on your frontend.
Your frontend should be designed entirely with ExtJS components. Either design your frontend with ExtJS or via HTML templates, but try not to do both, as it gets confusing and hard to maintain. I recently did this, and every controller action had a view that set up the DOM with some basic elements (a header for the page, any divs I needed to bind components to, and the .js file that was specific to that page/view).
Then, make your application RESTful. All of your ExtJS components can read data from a DataStore (or can just take a URL as the data source), so you just give them the paths you'd like and you're done.
Check out Bancha, it integrates ExtJS 4 and CakePHP 2.
It does this by doing all the communication in the background using an completely implemented Ext.Direct for CakePHP.
cheers
Roland