CakePHP and reusable approach - cakephp-2.1

I would develop my CakePHP application in the most reusable way. I'd like to treat it as webservices, so I don't want to strictly bind controller with view. My idea is: controller just returns json info, the view calls the controller and get the json and make html output.
How can I realize that? Could be a good approch, developing pages rather than views, and inside that pages call the webservices previously developed.

You can even forget about creating view files, using $this->set('_serialize', array('people')); in your PeopleController::show()

Well Cake is kinda' works like this "out of the box". You can use Router::parseExtensions(); to define what type of data you would like to serve. For example in app/Config/routes.php:
Router::parseExtensions('xml','json');
This will make it possible to detect what kind of request is incoming. For example if someone requests:
www.example.com/people/list.json or www.example.com/people/list.xml, in your PeopleController's list() method you'd be able to detect what kind of resource is being requested - json or xml, or of course any other
extension you define. This is what the RequestHandlerComponent is used for. You can check if it is xml for example:
if($this->RequestHandler->isXml()) {
//Some code
}
The different extensions are only different representation of the data, so it shouldn't matter what exactly you're serving. From v2.1 Cake will automatically switch the view class when it sees a JSON or XML request, which takes us to the new JSON and XML views.
All you will have to do is provide the views in the appropriate places.
In View/People (as for this example) you would have:
..View/People/
list.ctp
xml/
list.ctp - XML view
json/
list.ctp - JSON view

Related

Zend Framework 1 Ajax

Could somebody please suggest me a good beginner tutorial of using Ajax with Zend 1.I have been searching the net for some of this tutorials, but couldn't find an understandable one.In some they say you have to create a .json.phtml file for json response, the others don't.I am very confused about all these ajax calls with Zend Framework 1. Would be very grateful.
Well there really are some basic things.
Get your data (from DB, file, in-code array, whatever)
Get the controller helper
Send the JSON response
And that's it. OK, not exactly but basically yes!
Provided you have the data in $data:
$this->_helper->json($data, true);
will return a JSON response. The documentation is here.
Now there is the other notion of a Context Switch and AjaxContentHelper which:
The ContextSwitch action helper is intended for facilitating returning different response formats on request. The AjaxContext helper is a specialized version of ContextSwitch that facilitates returning responses to XmlHttpRequests.
To enable either one, you must provide hinting in your controller as to what actions can respond to which contexts. If an incoming request indicates a valid context for the given action, the helper will then:
Disable layouts, if enabled.
Set an alternate view suffix, effectively requiring a separate view script for the context.
Send appropriate response headers for the context desired.
Optionally, call specified callbacks to setup the context and/or perform post-processing.
Something like this:
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->setDefaultContext('json');
$contextSwitch->addActionContext('index', array('xml','json'))->initContext();
$contextSwitch->addActionContext('get', array('xml','json'))->initContext();
$contextSwitch->addActionContext('post', array('xml','json'))->initContext();
$contextSwitch->addActionContext('put', array('xml','json'))->initContext();
$contextSwitch->addActionContext('delete', array('xml','json'))->initContext();
$contextSwitch->addActionContext('head', array('xml','json'))->initContext();
You don't really need a tutorial I think. All you need is a good basic knowledge of how the web works internally and to read the Zend Documentation. Anyway here is some tutorial on ContextSwitch.

Getting partial view fragments with Spring MVC

I'm new in Spring MVC, I just started my first project and I'm doing some research to be sure to set it up in a proper way (should work in the long-term!).
I already know that for a part of the project, I will need to manually change small fragments of the page through Ajax. I know it's possible to change part of the page (using Tiles). What I really need, though, is for example to change a single line in a table containing dynamically generated data (i.e. data coming from the database).
Can you suggest anything?
I don't want to use JSF or Spring JS.
Thank you.
You have at least two choices:
render on the server, send the update html snippet to the brower and use JavaScript to replace them
send an AJAX request to the server, but this time return only the data (JSON) and the "render" the table line in the browser (or just update some pices of text)
For the fist choice you need a dedicated jsp file (and tiles configuration) to render only a single line. As fare as I know, there is no technical support.
What you can do, to reduce the amount of duplicated code is to use that single line rendering jsp in like in include in the one that renders the complete table.
Of course instead of using JSP to render the single line you can also use the Java Method that handles the request, and make it returning the html string.

Using Cake w/ url extensions

I am using CakePHP 2.0 (I believe it is v2.0.3.) and PHP 5.3.8.
I am working on an application which utilizes Cake's support for url extensions. Specifically, I am outputing XML whenever a url request ends in the .xml extension. If the url request is made without any extension, then my application presents the stardard view. This all works beautifully --
request .../controller/action.xml renders via view/controller/xml/action.ctp while request .../controller/action renders via view/controller/action.ctp.
To achieve this, I did the following:
1. Added support for url extension; added the following line to route.php -- Router::parseExtensions('xml');
2. Added support request handling; added the following line to MyController.php -- public $components = array('Session', 'RequestHandler');
To output xml, I am using Cake's 'XML' class in conjunction with PHP's 'SimpleXMLElement' class. My problem is that the complete xml is never generated. The classes are suppose to generate xml based on an input PHP array, however, it appears that the complete array is not processed. My xml output is partial.
My source code in my view file (.ctp) is as follows:
$simple_xml_elem = Xml::build($xml_array);
echo $simple_xml_elem->asXML();
Interestingly, in the course of trying to debug this problem, I discovered the a similar behaviour can be observed if I simple attempt to dump the view object within the xml view file (../view/controller/xml/action.ctp). 'var_dump($this)' only output a partial dump of the view. The same view dump performed within the standard view file (../view/controller/action.ctp) outputs a full dump of the view.
It is my believe that Cake is somehow setting up the view environment differently when it routes for a url extension than when the standard view is requested.
Could some please shed some light on the for me before I lose my hair. Please???? Thanks!
Have you looked at the response & request objects
http://mark-story.com/posts/view/the-cakerequest-object-in-cakephp-2-0 - the article was written when cake 2 was alpha I think but Mark talks about the concept of request object (another entry for response)
both objects are passed to the controller
http://book.cakephp.org/2.0/en/controllers/request-response.html
for now I believe you use the request comp to handle layout switching (although it can be done without it)

Django client side query construction

I'm making a pretty standard AJAXy (well, no XML actually) web page. The browser makes a bunch of API queries that return JSON to run the site. The problem is, I need to add to the API interface each time the page needs to do something new. The new API interface is usually little more than a database query followed by mapping the returned objects to JSON.
What I'd like to do is to get rid of all that server-side duplication and just have the page make database requests itself (using the model interface), but in a way that is safe (i.e. just read only ones). I think this would amount to an interface for constructing Q objects using JSON or something like that, and then send that up to the server, run the query, and return the results. Before I go making my own half-broken architecture for this, I'm wondering if this has already been done well. Also, is this even the best way to go about eliminating this duplication?
Thanks
Search multiple fields of django model without 3rd party app
Django SQL OR via filter() & Q(): Dynamic?
Generate a django queryset based on dict keys
Just replace with operator.and_ where appropriate.

Wicket and a rich ajax website: easiest way to do it?

I want to use Wicket to build an application, but I have some designers that would like to write/maintain the javascript, and they basically expect 1 JS-segment per page, and a global JS-file.
I think the most natural way to add javascript in wicket is to add it per component (not per page), which would create problems for those designers (fractioned javascript, and having to write it in java-files). Is there a better way to solve this?
(of course, I expect things to work after a partial refresh.)
And a second (related) thing they'd like (and I'd like actually) is the possibility to request information in JSON-format through a static link , is this possible in Wicket?
I started with JSON by making my wicket pages return the JSON, but quickly realized there are better tools for the job, especially if you will have a full web services layer. If you just need a little JSON here and there, always via a GET, then sure, just make a Wicket page.
I ended up using Jersey with Jackson alongside of Wicket. Jersey simplifies the configuration of URLs that can do different things with different http methods (GET/POST/PUT/DELETE), as well as easily parsing query strings, etc. I'd consider going this route for heavier JSON needs.
You can easily run both Wicket and Jersey in the same web application with a little web.xml configuration.
Wicket's built in AJAX support is always stateful and thus accessed with changing URLs. If your designers aren't planning to use Wicket's JS library, it's pretty straightforward to mount a JSON page:
public class JsonReturningPage extends WebPage {
public JsonReturningPage(PageParameters params) {
String json = "{foo: 4711}";
IRequestTarget t = new StringRequestTarget("application/json", "UTF-8", json);
getRequestCycle().setRequestTarget(t);
}
}
Alternatively, you could also implement your own AbstractRequestTargetUrlCodingStrategy to directly return an IRequestTarget from IRequestTarget decode(RequestParameters params) and mount it in your application.
Regarding JS files, I'd try to educate them to use one file per component. This certainly has the advantage of less copy-paste code and simpler maitenance. Additionally, I'd certainly discourage JS in Java code. It's normally only needed to pass data or config to JS , either as variable definitions or method calls. As this data is typically in Java and JS is written by designers, it's time for designers and programmers to team up.
Quick answer to your second question is yes it is possible. Use bookmarkable links to access a resource that returns JSON data.
You can easily use the following code to dynamically communicate with Wicket:
AbstractDefaultAjaxBehavior callme = new AbstractDefaultAjaxBehavior(){
#Override
protected void respond(AjaxRequestTarget target) {
}
};
page.add(callme);
//From any ajaxrequesttarget you can simply append the following code:
target.appendJavascript("wicketAjaxGet('"+callme.getCallbackUrl()+");");
This way you can have an ajaxlink etc... that will transfer the ajaxrequest to the Wicket side. If you want to pass data (though a static link doesn't sound like that) do the following:
"wicketAjaxGet('"+callme.getCallbackUrl()+"&x='+value_to_pass_back''";
//to Read the value in the respond:
String x = RequestCycle.get().getRequest().getParameter("x");
So the url to the callback is dynamically generated (as the callback url is specific to the session) but it is formed like any other url....
To me this is 10 times simpler than building a JSON system on top of wicket instead of using the one built into it.... I use this all the time and it works great for me at least. If your solution is different/better I would like to know why perhaps.

Resources