How can I get php class methods in AJAX Call? - php

I am creating a mobile app with Phonegap. Because the project is server-based, I use JQuery and AJAX to connect to php files lying on a server. Now I am having the following problem:
I make a AJAX call to, say, the php file login.php by
$.post('http://example.com/php/login.php',
{
}).success(
function(data){
console.log(data);
}).error(
function(data){
//return error
console.log("Error post ajax " );
},'json');
In login.php I want to use class methods, where the class is written in another php file, class.php.
So login.php looks like this
<?php
require_once('http://example.com/php/class.php');
$test = $class->test();
echo json_encode($test);
?>
and class.php looks like this:
<?php
class CLASS {
public function test(){
echo "test";
}
}
$class = new CLASS;
?>
But I can not use the method test() in the class CLASS. If I write the CLASS in the login.php file, of course it works, but this is not what I want.
Has anyone some tipps for me how to tackle this problem?

You should be instantiating the class in login.php by convention.
This:
$test = $class->test();
Should be this:
$test = new CLASS();
$test->test();
I think you said this is not what you want, so this might fix your issue:
You are not declaring the $class variable correctly:
This:
$class = new CLASS;
Should be this:
$class = new CLASS();

You need to learn a few basics, for example from this tutorial http://tut.php-quake.net/de/, and get some things straight. Many things you do are plain wrong
require_once('http://example.com/php/class.php');
you do not include like that, you include the raw path on your server, not an URL
require_once('/path/to/your/file/class.php');
More like this.
$test = $class->test();
this also will not work when your function looks like
public function test(){
echo "test";
}
this, your function has to return the value
public function test(){
return "test";
}
to achieve what you try.... consider getting some basics straight first would be my first advice, keep in mind I just want to help you because you will struggle more often if you don't get those basics and know the language you are using ;)

Related

How to call php functions and NOT php class in an AJAX call

Here is a very simple and silly question I'm going to ask:
I'm very new to PHP, I was wondering if there is a way to call just a function in a class of PHP by AJAX.
for instance something like this:
$.ajax({
url:'newPHPClass.php/My_Function_Name'
...
});
So in php, it would be like:
<?php
class newPHPClass {
function My_Function_Name(){
}
}
?>
Why do I need this? So I wouldn't have like so many php files. Instead I'll have a single php class with different functions inside. It will look cleaner and less extra files.
I have used ASP.NET MVC C# before. and in ASP.NET I could just simply put my controller's name in the URL section of AJAX followed by / and then my function's name (which could be modified in my Global.asax.cs file).
Thanks.
<?php
$action = $_POST['action'];
class Foo {
function execute($action) {
switch($action) {
case "method1":
$this->doMethod1();
break;
case "method2":
$this->doMethod2();
break;
}
}
function doMethod1() {
echo "Foo::doMethod1";
}
function doMethod2() {
echo "Foo::doMethod2";
}
}
$foo = new Foo();
$foo->execute($action);
?>
And use foo.php?action=method1 as URL.
First of all you don't call functions or methods via AJAX, you make a request to a page.
If you make an AJAX call to a PHP file like:
<?php
class newPHPClass {
function My_Function_Name(){
}
}
?>
nothing will be returned and nothing will happen server side other than allocating the space for that class and then immediately destroy it at the end of the request.
For your question: it doesn't really matter on the client side (Javascript) how you are going to manage the class and files organization: only one file is going to be requested by an AJAX call.
I'd suggest you to have at least two different files: the declaration of functions or classes and the file that manage the response. You need a bit a separation from execution and declaration, therefore I'd avoid things like:
class A { ... }
$a = new A;
$a->myMethod();
Depending on the AJAX output I'd go with something like this instead:
# class.php
class A {...}
# ajax.php
$a = new A;
$a->myMethod();
Finally a suggestion: don't use classes when they just don't make sense. Having a bunch of functions grouped inside a class doesn't really feel OOP to me. I think you are using classes with procedural code in mind. Therefore I would go with a file that declares a bunch of functions instead.

CakePHP How to call a controller function from an external function

I'm having trouble with accessing the session in an external .php script located in webroot.
Thought I'd write a function getSession() in one of my controllers and try to call it in the .php file.
So in steps:
I have file.php
In a controller I have a function getSession().
How to call the controllers function in the file.php?
Thank you.
EDIT
Meanwhile I fixed my bug, but still am curious how this is done and want other stack users to find a good answer to this so:
Its exactly like this:
In UsersController I have a function:
public function getSession() {
return $_SESSION['Auth']['User']['user_id'];
}
That I want to let's say print (for example) like this: print_r(Users.getSession) in the file test.php located in webroot/uploadify/test.php.
This file is not a class, but if it is required, then it shall be :)
#CaboOne: Maybe your answer was correct, I just wasnt sure what code to call (and enter) where :)
Supposed I have the following php file in webroot folder:
<?php
class TestingClass {
function getName(){
return "Test";
}
}
?>
I would do the following:
// This would bring you to your /webroot folder
include $_SERVER['DOCUMENT_ROOT'].'/another_file.php';
// Initializing the class
$example = new TestingClass;
// Call a function from the initialized class
$a_value = $example->getName();
// If you want to use $a_value in the view, you can then set
$this->set('a_value', $a_value);

replicating a feature in zend

I have been pouring over Zend_View and the various classes and interfaces that make up the view. One thing I am attempting to replicate in a project that does not use zend in any way shape or form is the:
$this->view->variable = 'Hello world';
that you can set in a controller and then do:
echo $this->view->variable;
My ultimate goal is to do something like:
$this->variable = new SomeClass
and then else where, in a view specifically, do:
$this->variable->someMethod();
My question is:
How would I replicate what zend does to do something simmilar with out using global variables?
How is zend able to do something like $this->view with out ever instantiating or saying what view is?
this would help me understand how, variables are passed around or objects are passed from the logic to the view and how php allows for something like $this->view to work when in a view or not.
note: this is not a Zend specific question and "use zend" is not the answer. I am looking to replicate a specific feature. My project does not in any way use or affiliate with zend.
I don't know why exactly you want to achieve this, but as a super simple setup (which is by no means suited to be the basis of an MVC framework) you can look at this:
<?php
class Controller
{
private $view = null;
public function __construct()
{
$this->view = new View();
$this->view->someVar = "foobar";
}
public function render()
{
include "view.php";
}
}
class View
{
}
$controller = new Controller();
$controller->render();
And then, in view.php, you can do:
<?php
echo $this->view->someVar;
Beware: This code only shows HOW it's possible to achieve such a construct, it does not anything useful at all ;).
It's actually pretty simple. When you use include, require, eval et al., the loaded code is brought in to the current scope. So if you have a template file
template.php
<span><?=$this->view->somevar?></span>
Controller.php
<?php
class Controller
{
private $view;
public function doSomething()
{
$this->view->somevar = 'Hello World';
include 'template.php';
}
}
index.php
<?php
require 'Controller.php';
$oC = new Controller();
$oC->doSomething();
Blamo.., template.php is able to call $this->view->somevar as it is treated as part of Controller.php. Running php index.php on the CLI produces
<span>Hello World</span>
To elaborate a tiny bit, if $this->view inside of Controller.php were a class you've defined rather than a simple instance of stdClass as in the above demonstration, and it had a function someMethod, you could call $this->view->someMethod() from template.php just the same.

php class constructor

Hi I have a class as follows:
<?php
include '(OrderContainer.php)';
class OrderAuthenticator
{
private $OrderObj;
public function __construct($Order)
{
$this->OrderObj = $Order;
echo 'Created an instance os OrderContainer<br/>';
}
//Misc methods.....
}
?>
Then I have a method that tries to instantiate this object
<?php
include ('OrderAuthenticator.php');
$Authenticator = new OrderAuthenticator($OrderObj);
?>
Problem is that in the object is not instantiated.....
No matter what I do ..... Im new to PHP so I was wondering if there is something quite obvious here that Im not doing?
Could someone please give me a hand..
Thanks
It seems as include '(OrderContainer.php)'; should be include('OrderContainer.php'); instead.
Make sure $OrderObj is defined in the main script creating an instance of OrderAuthenticator.
To debug, be sure that PHP is showing error messages by starting with error_reporting(E_ALL); ini_set('display_errors',1); first in the main script.
Also, make sure you have no syntax error (for example, by printing "Hello world" in your script).
You need to create an $OrderObj to be passed in to the constructor
Just remove public from constructor.

Avoiding Multiple Class Instantiations of Single Class PHP?

I've got a class I wrote to work with the front end (web browser side) of a shopping cart.
It's fairly simple in that I send the class a product ID that I bury in the URL and then query a database populating the classes variables for use in retrieving the data through some public methods.
To interface with my actual physical web page I have a file I call viewFunctions.php. Wherein I instantiate my class called ItemViewPackage():
<?php
require_once(dirname(__FILE__) . '/ItemViewPackage.php');
$viewObject = new ItemViewPackage($_GET['page']);
So, I have shoppingcartpage.php (the physical url) that requires the file viewFunctions.php that loads my class ItemViewPackage().
The output page shoppingcartpage.php calls functions like get_item_info('title') or get_item_info('price') which in the viewFunctions.php file is made like so:
function get_info($type){
echo $viewObject->get_info($type);
}
Now, right off the bat, this isn't working because, I assume, $viewObject is not global. So I make $viewObject global like so:
function get_info($type){
global $viewObject;
echo $viewObject->get_info($type);
}
But, this doesn't work either, I still get an error for "Call to a member function get_info() on a non-object"
Now, the only thing that works is:
function get_info($type){
$viewObject = new ItemViewPackage($_GET['page']);
echo $viewObject->get_info($type);
}
But, I don't want to re-instantiate my object every time I make a call to this function (which is several times for several bits of information). I'd rather instantiate once at the top of my viewFunctions.php doc and use that object every time I call this function.
Am I going about this completely wrong?
Thanks in advance.
DIAGRAM (hopefully it helps visualize)
What for do you need viewFunctions.php anyway? It's only wrapping the ItemViewPackage. Remove that and use the ItemViewPackage directly, e.g.
// shopping.php
include_once 'ItemViewPackage.php';
$viewObject = new ItemViewPackage($_GET['page']);
<div><?php echo $viewObject->get_info('title'); ?></div>
<div><?php echo $viewObject->get_info('price'); ?></div>
Then you dont have to bother with globals or Singletons. If you dont want a second instance, dont instantiate a second one. It's simple as that in PHP. If there is anything in viewFunctions.php that modifies the output of the $viewObject instance, consider making that into a class and have it aggregate the $viewObject into a property, e.g.
// viewFunctions.php
include_once 'ItemViewPackage.php';
$viewObject = new ItemViewPackage($_GET['page']);
$helper = new ViewObjectHelper($viewObject);
then you can access the $viewObject from within the Helper object with $this->propertyName.
As for reducing load to the database: this is a solved problem. Consider using a cache.
You want the singleton pattern, please see this answer:
Creating the Singleton design pattern in PHP5
This allows you to get an instance of your class in any scope, and it will also be the same instance.
What scope is the $viewObject created in?
Note: that even though it appears to be in the global scope because it is not in a function within the shown file, if the file is included from within a function it will be in that scope...
i.e.
file1.php
include 'file2.php';
function includefile($file) {
include $file;
}
includefile('file3.php');
file2.php
$global = 'this is global';
file3.php
$notglobal = 'this is not';
<?php
require_once(dirname(__FILE__) . '/ItemViewPackage.php');
$viewObject = new ItemViewPackage($_GET['page']);
function get_info($type){
global $viewObject;
echo $viewObject->get_info($type);
}
This should work from viewFunctions.php and any file that includes it such as shopping.php. So from shopping.php we can do either:
echo get_info($type);
or
echo $viewObject->get_info($type)
This alone raises some logical flags in my head. Not sure why you want to wrap the object again.

Categories