Calling PHP class in Angular - php

I have a PHP-class handling authorization and requests to an API and I would like to use those functions in Angular. When the PHP is loaded I create a controller which initializes a variable which should contain the response from the API. I think it should look something like this:
$scope.jsonData = <?php echo json_encode(PHPClass::getData("Argument")); ?>;
Is there any way to do this and use the PHP-class and refrain from using $http?

I realize I've been going about this the wrong way. I'll instead start looking into it properly authorizing the requests through angularjs.

Related

Sending correct JSON content type for CakePHP

In my CakePHP app I return JSON and exit for certain requests. An example of this would be trying to access the API for a login as a GET request:
header('Content-Type: application/json');
echo json_encode(array('message'=>'GET request not allowed!'));
exit;
However I am having to prefix the echo with the content type in order for it to be sent as JSON. Otherwise my code at the other end interprets it different.
Any ideas on how to get around this? Or at least improve it.
Update: Cake version 2.3.0
You can leverage the new 2.x response object:
public function youraction() {
// no view to render
$this->autoRender = false;
$this->response->type('json');
$json = json_encode(array('message'=>'GET request not allowed!'));
$this->response->body($json);
}
See http://book.cakephp.org/2.0/en/controllers/request-response.html#cakeresponse
Also you could use the powerful rest features and RequestHandlerComponent to achieve this automatically as documented: http://book.cakephp.org/2.0/en/views/json-and-xml-views.html
You just need to allow the extension json and call your action as /controller/action.json.
Then cake will automatically use the JsonView and you can just pass your array in. It will be made to JSON and a valid response by the view class.
Both ways are cleaner than your "exit" solution - try to unit-test code that contains die()/exit(). This will end miserably. So better never use it in your code in the first place.

access PHP Methods with jQuery

I'm completely new to jQuery and Ajax, but I've managed to learn how to do the Hello World, populate a select tag, etc, etc...
Problem is, I don't like to use structural PHP. The way I learned I have to call some PHP file with $.getJSON and that file has to "echo" my result.
What I want is to be able to call a PHP file that is actually a class with some methods and the return of the method would be what JavaScript would receive instead of just an echo result.
Thanks for your attention.
Ps.: I have a lot of experience with PHP-OOP and Flex+PHP using Amfphp. I'm trying to build a different version of view and I would like to re-use the classes that Flex already use.
jQuery runs on your computer, and PHP runs on the server. PHP and jQuery can only communicate via a series of well-crafted strings. On the server, you are free to create objects, run methods, manipulate output, and anything else. However, if you're going to be feeding that data back into your jQuery application (still running on the client's machine), you'll need to echo (or output) the results of your PHP script.
You may consider something like this:
$.post('server.php', { 'class':'foo', 'method':'bar' }, function( response ) {
/* do something with the output of $foo->bar(); */
});
As you can see here, I can define the class and method I'd like to have called on the server. From server.php, we would look to $_POST['class'] and $_POST['method'] to determine what we will instantiate, and which methods we will run.
The AMF is somehow different from HTTP, they're different protocols.
When using AJAX (jQuery or not), you're calling HTTP methods on URIs, not OOP methods. So everything ends up in a minimum of two mappings:
Your application logic mapped to methods and URIs.
Your Javascript code mapped to methods and URIs.
Here is a sample using Respect\Rest:
$router->get('/users/*', function($userName) {
return MyDatabaseLayer::fetchUser($userName); //Illustrative
})->accept(
'application/json' => function($data) {
header('Content-type: application/json');
return json_encode($data);
}
);
Now the jQuery part:
$.getJSON('/users/alganet', function(user) {
alert(user.name);
});
You should use appropriate HTTP methods for different actions. Saving an user would be something like:
$router->post('/users/*', function($userName) {
return MyDatabaseLayer::saveUser($_POST['user']); //Illustrative
});
jQuery:
$.post('/users', $("$userform").serialize());
There are four main HTTP methods: GET, POST, PUT and DELETE. GET and POST are the most common ones.
There is a nice trivia: Both HTTP, REST and AMF were written by the same guy: Roy Fielding.

Creating a web service in PHP

I would like to create a web service in PHP which can be consumed by different consumers (Web page, Android device, iOS device).
I come from a Microsoft background so am confortable in how I would do it in C# etc. Ideally I would like to be able to provide a REST service which can send JSON.
Can you let me know how I can achieve this in PHP?
Thanks
Tariq
I developed a class that is the PHP native SoapServer class' REST equivalent.
You just include the RestServer.php file and then use it as follows.
class Hello
{
public static function sayHello($name)
{
return "Hello, " . $name;
}
}
$rest = new RestServer(Hello);
$rest->handle();
Then you can make calls from another language like this:
http://myserver.com/path/to/api?method=sayHello&name=World
(Note that it doesn't matter what order the params are provided in the query string. Also, the param key names as well as the method name are case-insensitive.)
Get it here.
I would suggest you go for Yii it is worth of learning. You can easily establish it in this.
Web Service. Yii provides CWebService and CWebServiceAction to simplify the work of implementing Web service in a Web application. Web service relies on SOAP as its foundation layer of the communication protocol stack.
Easiest way in PHP is to use GET/POST as data-in and echo as data-out.
Here's a sample:
<?php if(empty($_GET['method'])) die('no method specified');
switch($_GET['method']){
case 'add': {
if(empty($_GET['a']) || empty($_GET['b'])) die("Please provide two numbers. ");
if(!is_numeric($_GET['a']) || !is_numeric($_GET['b'])) die("Those aren't numbers, please provide numbers. ");
die(''.($_GET['a']+$_GET['b']));
break;
}
}
Save this as test.php and go to http://localhost/test.php?method=add&a=2&b=3 (or wherever your webserver is) and it should say 5.
PHP does have native support for a SOAP server ( The SoapServer class manual shows it) and I've found it pretty simple to use.
Creating a REST style API is pretty easy if you use a framework. I don't want to get into a debate about which framework is better but CakePHP also supports output as XML and I'm pretty sure others will as well.
If you're coming from a Microsoft background just be careful about thinking about "datasets". They are a very specific Microsoft thing and have been a curse of mine in the past. It's probably not going to be an issue for you, but you may want to just see the differences between Microsoft and open implementations.
And of course PHP has a native json_encode() function.
You can check out this nice RESTful server written for Codeigniter, RESTful server.
It does support XML, JSON, etc. responses, so I think this is your library.
There is even a nice tutorial for this on the Tutsplus network -
Working with RESTful Services in CodeIgniter
You can also try PHP REST Data Services https://github.com/chaturadilan/PHP-Data-Services
You can use any existing PHP framework like CodeIgniter or Symfony or CakePHP to build the webservices.
You can also use plain PHP like disscussed in this example

PHP OOP and AJAX: How to handle serverside in Class?

I'm working on converting my standard PHP project to OOP but I ran into a wall about how to handle AJAX calls with PHP Classes. I'm not happy with the way I'm doing this now. I have a TillAjax.php file which I call from my TillUI.php file from a AJAX call.
In the TillAjax.php file I do this to get the information passed from the ajax call.
$till = new Till();
if(isset($_POST['data']))
$till->doStuff($_POST['data']);
I think this ruins the OOP.
I have worked with ASP.NET MVC and here its possible to call a specific action in a controller without i have to check for the post value. So I want to know if there is a smarter PHP way to solve the above problem?
The method I use for this is to have an Ajax class.
Your php file calls Ajax::Process($_GET['handle']), where 'handle' contains the name of a static class method, so perhaps 'Till::Process'. The Ajax class checks the function against a list of permitted functions (i.e. functions that you are allowing to be called via ajax), and then uses call_user_func_array to call the function (my code uses the contents of $_POST as arguments to pass to the function). The return of that function is automatically encoded as json and outputted to the client.
This means that your target php file looks like this:
<?php
//File: ajax.php
include ("Ajax.php");
Ajax::Process($_GET['handle']);
?>
Which I think is pretty simple.
Then you can have javascript that looks like this (jquery) :
$.get('ajax.php?handle=Till::Process', {}, function(result) {
//called on page response
});
So then result now contains whatever data is returned from the php method Till::Process.
Have you considered using a PHP MVC framework such as CodeIgniter, CakePHP, Kohana, etc? They will let you route requests to specific controller methods. It will be a much cleaner solution if migrating to one of these frameworks is an option for you.

Best Practice for returning cross-site JSON response

I'm currently working on a small application that works like this:
When the user clicks a link, an Ajax GET request is fired.
The request hits a server-side PHP script.
The script, which requests information for another domain, retrieves a JSON feed.
The feed is then echoed back to the client for parsing.
I'm not really a PHP developer, so I am looking for some best practices with respect to cross-domain requests. I'm currently using file_get_contents() to retrieve the JSON feed and, although it's functional, it seems like a weak solution.
Does the PHP script do anything other than simply call the other server? Do you have control over what the other server returns? If the answers are No and Yes, you could look into JSONP.
You might want to abstract the retrieval process in PHP with an interface so you can swap out implementations if you need too. Here is a naive example:
interface CrossSiteLoader
{
public function loadURL($url);
}
class SimpleLoader implements CrossSiteLoader
{
public function loadURL($url)
{
return file_get_contents($url);
}
}
Comes in handy if you need to test locally with your own data because you can use a test implementation:
public ArrayLoader implements CrossSiteLoader
{
public function loadURL($url)
{
return json_encode(array('var1' => 'value1', 'var2' => 'value2'));
}
}
or if you just want to change from file_get_contents to something like curl

Categories