I am trying to build an android application based on hotel management. The app simply provides the list of deals to the user. The website stores the data regarding the user and deals in sql tables in database.
Is there any simple way to communicate data such as deal details and user details like user name, hotel name, etc. from website to android app and viceversa.
I know this is possible using json. But I am finding it difficult to implement.
it is very painless using https://code.google.com/p/google-gson/ on android and json_encode() in PHP (take also a look on blackpanthers response) and here a short excerpt how to bind that thing in java on a concrete sample:
first implement json_encode() in PHP and call in in a browser so you can see the result, say, you get something like:
{"user_name":"my name", "user_surname":"my_surname", "phones": { "mobile":"11111" }}
now, you've got a JSON entity containing a properties "user_name", "user_surname", and "phones". whereas "phones" is a nested entity, containing a property "mobile".
now you create a java-class per entity, so we need two, the one containing the "phones" and the other one containing all properties, including the entity "phones"
class Phones {
// with this annotation you can bind to
// properties from JSON named differently than
// the property in this class
#SerializedName("mobile")
String thePhone;
}
class MyJson {
String user_name;
String user_surname;
Phones phones;
}
well, thats it :) ah ok, the final part
...
InputStream is = new URL("http://www.my.php.returning.json").openStream();
InputStreamReader isr = new InputStreamReader();
MyJson myJson = new Gson().fromJson(isr , MyJson.class);
... //close stream, handle exceptions, etc.
// now you've got that all in the myJson object...
here you go!
You may find the following tutorial useful: http://www.helloandroid.com/tutorials/connecting-mysql-database
This tutorial shows how you can use the MySQL database and PHP to send JSON to an android application.
(This is assuming you are using a MySQL database, if not, it is still a useful tutorial).
You can also use GSON, Google's API and the following tutorial:
http://www.techrepublic.com/blog/app-builder/use-gson-to-work-with-json-in-your-android-apps/1386
Related
I have just worked in the front-end part alone. So I am not sure how to connect or fetch data from a database. If I am using a tomcat server will I be able to do that using PHP?
I am thinking of creating the project in eclipse. I am not sure how to connect that with PHP either.
if you will use Spring as back-end than you need to create model, controller and DAO. Also, you have to create connection to DB. In controller, you have to create method that will call query from DB. After you've created back-end you have to call http.get method inside of js.
e.g.:
$http.get('/user/retrieve/' + $scope.authorization.userName).success(function(data) {
$rootScope.getName = data;
})
.error(function(data){
$rootScope.getName = $scope.authorization.userName;
});
}
After you've created http get method, if call was successful data won't be empty, so you can store it into $scope variable.
To show values of $scope just put double curly brackets around name of $scope like this {{ getName }}
There are plenty of tutorials how to get data from mysql using Spring or php.
I'm giving you some insight by posting link of tutorial: http://websystique.com/springmvc/spring-mvc-4-angularjs-example/
Hope this will help you!
We are developing an application in Symfony (2.7) that deals with third party entities and usually needs to transform (or fill) objects from one subsystem to another.
Take this example where we need to fill $destinationObject with data stored in $sourceObject:
$sourceObject;
$destinationObject = new DestinationObject();
$destinationObject->setProperty01($sourceObject->getProperty01());
$destinationObject->setProperty02($sourceObject->getProperty02());
$destinationObject->setProperty03($sourceObject->getProperty03());
$destinationObject->setProperty04($sourceObject->getPropertyWithDifferentName());
$intermediateValue = explode('/',$sourceObject->getProperty04());
$destinationObject->setProperty05($intermediateValue[0]);
$destinationObject->setProperty06($intermediateValue[1]);
Manual method (or no method) leads to duplicated code, copy&paste practices, etc.
So my question is:
Where is the propper place to implement this kind of "transformations"?
My ideas so far:
Doing it as a model method like $destinationObject->loadFromSourceObject($sourceObject) is a bad idea (entity coupling)
I don't like the idea of building an utility class full of static methods
...
EDIT: Also, there's a common situation where in $destinationObject we need to load data from both $sourceObjectFromClassA and $sourceObjectFromClassB, so SourceObjectToDestinationObjectTransformer understood as a method returning a new created DestinationObject is not a valid option. I mean, something like this may be needed (bad code coming warning, just for exemplification purpose):
$destinationObject = new DestinationObject();
$destinationObject->loadFromSourceClassA($sourceObjectFromClassA);
$destinationObject->loadFromSourceClassB($sourceObjectFromClassB);
Alright so I'm trying to make some sense of all these patterns.
Alright, so I'm coding an applicantion in CodeIgniter which needs to be able to send data about a car and a customer to different types of companies using SOAP, maybe XML, comma-separated and so on.
But they all need the same thing.
I wanna make it as dynamic as possible and make sure it's easy to write tests.
So the service should take a couple of things:
a handler
applicants [1-2]
params
object
I started up creating different classes
Gr8Exp
NordCar
SwePerf
each implementing the interface iServiceRequest
interface iServiceRequest{
/**
* Send the request to the company server.
*/
function sendRequest();
/**
* Saves the response into the database.
*/
function saveResponse();
/**
* Prepares the request to the company, setting info from form and shit.
*/
function prepareRequest();
/**
* Soap, XML, CSV, JSON
* #param type $method
*/
function setRequestHandler(iServiceRequestHandler $handler);
}
Then they need to structure up the Soap, XML, CSV, JSON request depending on what handler i put in.
After those who needed to be validated (not all did) I used:
interface iAdaptServiceRequest{
/**
* Structure the array information and put it into an object structure in the right place.
*/
function structure(array $info);
/**
* Make all the checks for the function
*/
function validateInfo();
}
But I'm stuck, It worked really good when I just used SOAP request; but now. Since I need to format them differently, use a different handler for each type of request or company I don't know what to do.
I could put them i different folders and recreate the class in the different folders. But that's not a good practice since I'm duplicating code all over.
In the end I want to run some chaining like this:
$result = $m->prepareRequest()->sendRequest()->saveResponse();
Any suggestions??
IMHO:
-- create/use a front controller.
-- The front controller determines which request handler to use (JSON, SOAP, XML, etc).
-- The request handler generates a common "Request" object that behaves the same across all interfaces, basically putting variables into a common named format inside a "Request object"
-- It determines which service to send the request to and sends the request object there
-- The service processes the request object and generates a response object
-- The controller creates an appropriate (JSON/SOAP/XML) View object to process the response object into the correct view type and the View outputs your response as that type.
I would use something like yours: $result = $m->prepareRequest('JSON')->sendRequest()->saveResponse();, but specifing what format of data I'm sending.
The method prepareRequest(string $type) would check the format and call another method to convert your data to the respective format.
Something like this:
function prepareRequest(string $type){
if ($type == 'json'){
$this->convert2json();
}
if ($type == 'xml'){
$this->convert2xml();
}
// And so on
}
There is often confusion about the MVC or Observer pattern. This is not a situation in which this pattern is applicable. In the MVC pattern are the View and Model related to one another. The View must update itself based on information of the subject. A view and the underlying tables in a database are a good example. That is not what you want here.
The design pattern which suits this problem is the Builder pattern. The Builder pattern consists of four cooperating classtypes:
1. a Builder,
2. a ReaderManager,
3. a ConverterManager, and
4. a DataObject.
The ReaderManager is using the Interpreter pattern. Conversion can be done using the State pattern. What is the output of the ReaderManager (some DataObject) is the input for the ConversionManager. That can be done using an abstract class instead of an interface (my preference for data focused classes). The Builder connects the ReaderManager with the ConverterManager and takes care of the transport of data.
Some years ago I wrote about design patterns. The builder pattern was one of the patterns I described and this is the link to that page:
http://www.loekbergman.nl/InsideArchitecture/TheProcess/DesignPatterns/Builder
It shows a UML diagram of the pattern.
In the next link you can download a jar with some examples of design patterns. One of them the builder pattern:
http://www.loekbergman.nl/InsideArchitecture/DownloadsAndLicense
I have written this code several years ago, therefor do I give you this code without warranty. (Is that the correct term in this context?)
In the code you can see a folder with the name specifications. That is another example of the Interpreter pattern. (In the Builder pattern there is of course also an example of this pattern).
To be complete is here the link to the MVC - pattern:
http://www.loekbergman.nl/InsideArchitecture/TheProcess/DesignPatterns/Observer
and the Interpreter pattern:
http://www.loekbergman.nl/InsideArchitecture/TheProcess/DesignPatterns/Interpreter
So essentially I find myself writing a bunch of boiler plate code that takes info from a JSON encoded string and puts that data into the models used in my MVC web app. Is there an accepted method of doing this? Should every model have an associative array to model object converter? Should there be a utility class I write to do this? Basically, I am just trying to remove that code from my controllers to slim them down and I am new to PHP MVC. I am using Kohana 3.2 if that is of any relevance to the question.
EDIT:
I was asked to clarify. I receive data in string format that is JSON encoded (from a web service of my own writing - Java /w Jersey). So essentially, the models in my web app are not pulling their information from a database, but rather from a web service. Since the web service returns everything in JSON format, I find myself writing code that deals with that issue. The other way around, I can tell the GSON google code to convert JSON to a particular Java object. There does not seem to be a one liner way to do this in PHP. I am not talking about the stdClass object, but a model.
Your model must implement simple interface with method fromArray($array)
public function fromArray(array $array)
{
foreach($array as $property => $value) {
if(property_exists($this, $property) {
$this->$property = $value;
}
}
}
Kohana's models (ORM calss) only works with databse records. If you'd like to use Kohana you'll have to write new module based in ORM module. This module can have the actually do same things with model (load, save) but it's gona work with you input data.
I'm working with a PHP MVC Framework. Works really well. I like the separation of the business layer (model) with the business logic (controller). But i just stumbled upon a problem. Here's the thing:
Suppose i navigate to the following url:
http://localhost/user/showall/
In this case the userController.php is called and within that file there is a method showallAction() which gets executed.
In the showallAction() method i simply do a request to a model which gets all the users for me. Something like this:
public function showallAction()
{
// create userModel object
$users = new userModel();
// get all users and assign the data to a variable which can be accessed in the view
$this->view->users = $users->getAllUsers();
// render views
$this->view->render();
}
So this method gets all the users, assigns the data returned from the userModel to a variable and i can easily work with the returned data in my view. Just a typical MVC thing.
Now here comes the problem.
I also need to create a native iphone variant. Ofcourse the looks will be totally different. So all i actually want to do is to request this url:
http://localhost/user/showall/
And that it just gives me the array (in json format) back. So i can use that for the mobile development.
But this obviously can't be done right now because the showallAction() method assumes that it is for web browser display. It doesn't echo JSON formatted, instead it simply assings the array of users to a variable.
So that means i have to create another method "showallMobileAction()" in order to get the data, but specifically for the mobile device. But this is not an elegant solution. I'm sure that are better ways...
Anyone any idea how can i solve this problem??
In your situation i would modify the routing mechanism.
It would be useful, if you could add extension at the end of URL, which represents the format you expect, like :
http://foo.bar/news/latest >> HTML document
http://foo.bar/news/latest.html >> HTML document
http://foo.bar/news/latest.rss >> you RSS feed
http://foo.bar/news/latest.json >> data in JSON format
It's a simple pattern to recognize. And you can later expand this to add .. dunno .. pdf output, or Atom feeds.
Additionally , two comments :
Model is not a type of objects. Instead it is a layer, containing objects responsible for business logic, and objects responsible for data storage/retrieval.
View should be a full blown object, to which you bind the domain objects (objects responsible for business logic).
You could pass parameters to your url:
/user/showall/json
and get the third URL segment with a custom function or a built-in one. For instance, with CodeIgniter: $this->uri->segment(3).
Some frameworks will pass the additional parameters to your method. Just try this with the URL I wrote above:
public function showallAction()
{
print_r(func_get_args());
}
I'm not familiar with PHP MVC but in general terms I'd use the "accepts" HTML header field to request the response in either "text/html" or "text/json", the controller would check for the accepts type and return the response accordingly.