In code igniter web application we can can the controller and methods like domain-name/controller/method_name.Is there any way to access core PHP class methods like the same way?
How can i access the method in browser like domain/car/hello
The Car.php file is in the server root xampp/htdocs/Car.php
My class file Car.php:-
class Car{
public function hello()
{
echo 'Hello';
}
}
Please help.
You don't. The browser talks to the server (to PHP) using HTTP. HTTP has absolutely no notion of functions, or even what a programming language is. PHP also has no mechanism to allow anything to directly access/call a function from outside. The only thing that happens is that the web server decides based on the requested URL which PHP script to execute. That's all. Execution will always start on the first line of the script being executed, not directly in a function somewhere.
You can/have to write code which inspects the requested URL or otherwise decides which function to call, and then call it in PHP code.
Php is a server-side programming language, you simply cannot execute it in your browser without HTTP Server.
Upd: if you mean how can you run it in xaamp then you should run it. Run this by calling file like simple url page, for example localhost/Car.php
Try something like this:
<?php
Car $car = new Car();
$car->hello();
class Car{
public function hello(){
echo 'Hello';
}
}
Related
includepage.php
<?php
echo $variable;
?>
localpage.php
<?php
$variable = 'Content';
include 'includepage.php';
?>
How do I properly have a local page give a variable to an include. I was thinking classes, and I tried to instantiate it but couldn't get it to work in my specific circumstances. I have a page that is a template of content for all pages and the $variable is the content specific to each local page. What I listed above works but it's not good practice I'm told.
You should never have code in an include file which is invoked at the time the code is included. Your include file should only contain constant, class and function definitions. The code is then:
more predictable
easier to reuse
less likely to expose backdoors to your application
Of course, as with every rule there are exceptions, but the only one I can think of which has any merit in this context is when you are using an auto-prepend include to modify the behaviour of the environment while deliberately not modifying the application code (e.g. using a custom session handler with an off-the-shelf application).
You seem to be describing a front controller pattern - where requests for different functionality are first routed to the same php script. The term "templating" is typically applied to the opposite of this architecture - where the page layout for multiple seperate php scripts is handled by a common include file.
I tried to instantiate it but couldn't get it to work in my specific circumstances
Try again. You're never going to be able to build an application of any complexity without functions or classes.
tehpage.php
<?php
class tehpage {
public function __construct($parameters = null) {
//i.e. the parameters may determine which content is shown
$this->content = "page content";
}
public function htmlOut() {
echo $this->content;
}
}
?>
actualpage.php
<?php
include "tehpage.php";
$page = new tehpage($variousparametersyoulikeIlikearrays);
$page->htmlOut();
?>
Like so ?
My sidebar has elements that are the same in all my views, so instead of calling them over and over in all my controllers, I created a MY_Controller class and make variables available from there. Problem is, the content from my variables come from a file, so now everytime my site is loaded I'm making a call to read the file. It was pointed out to the me that this is not too good.
So what I'm trying to do is read the file in a model, then store it in a variable and then pass that variable to MY_Controller. Problem is I'm facing the same issue only now instead of reading the file from MY_Controller I'm reading it from the model. So I tried to create in a different function a variable that would be available in my entire model, and then a function that returns that variable, but it is not working. Here is my code:
Model:
class My_model extends CI_Model {
public $report = null;
function read_file()
{
$this->report = file_get_contents('/path/to/file');
}
function get_file()
{
return $this->report;
}
}
MY_Controller:
class MY_Controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('My_model');
$report = $this->My_model->get_file();
...
}
}
Right now $reportis returning null.
The read_file() function should be called once a day, because the file is updated daily in the morning. Any tips pointing if it is possible to do what I'm trying, or if there is a better way would be greatly appreciated.
I'm not going to give you code, because it would take too long, but I will explain how Symfony2 does it. Heard of Twig? Well, regardless of whether you are familiar with it or not, the important part of it is how it compiles templates.
It compiles all template logic and text to PHP files filled with generated functions and strings. The first time the template is executed this compilation is performed. The second time, the compiled PHP is re-used.
The IO in effect still takes place, but only on the included PHP pages. You can eliminate this again by bootstraping your entire source into a single file (Symfony does this with libraries, but not templates).
So, in order to "cache" your content to PHP, you need to write a PHP dumper (or using an existing one), or use var_export on simple data structures to dump your pre-loaded data.
You should call read_file function before get_file, also there is no relation between calling the function read_file and the updating of the file.
I was programming an application using php and pthreads and I noticed that it was't working correctly. In order to isolate the error I reduced the code, and now I have this piece of code, and I've checked that it behaves differently when executes it through the console than trought a web browser, and I can't find why, I'm here for help. The code is:
<?php
echo "beforethread<br/>";
class AsyncOperation extends Thread
{
private $sum;
public function __construct()
{
$this->sum = 5;
}
public function run()
{
echo "insidethread<br/>";
}
}
$thread = new AsyncOperation();
$thread->start();
$thread->join();
?>
through console I get:
beforethread
insidethread
and through a web browser:
insidethread
beforethread
I can't understand if php executes line by line why through web browser the code doesn't behave correctly. Any help will be appreciated. Thank you.
You should not write standard output in a web environment from any thread other than the one responding to the request. This is not safe, at least you will experience garbled output and at worst segmentation faults (since you are filling the buffer for stdout from another thread, which is not allowed, zend provides no way to abstract this).
Even at the console, if you want to make sense of your output you should use a mutex when writing to stdout.
I am having a controller IndexController.php in which action is something like this
class IndexController extends CustomControllerAction {
public function preDispatch() {
if (!$this->view->authenticated) {
$this->_redirect('/users/login');
}
}
public function indexemailAction() {
//somecode which calculates certain things
}
}
NOw,I need to call the action "indexmailAction" inside the IndexController.php with an independent php file
The php file is indextest.php
<?php
//Need to write some code to call indexmailAction in IndexController.php
?>
What should I write in this file ......
Thanks in advance
I know this is a few years old, and this may not be the intended use of the classes/functions, but I've found the following quite useful in isolated files that are called from the command line.
The problem this solves for me is that it eliminates spawning of Apache processes. The solution is great because I can access the some Controller/Action needed that I would from the URL.
In almost any ZF1 based app, you can copy your index file and keep everything the same and just comment out the following line.
$application->run();
Anything below this line you can access with your autoloaders etc. It's crude, but it works. Unfortunately, you'll soon find yourself with limited access to a lot of the files your application has, and the feeling the only way you can access the files needed is through a Controller/Action.
Instead, I use the following in a new file below $application->bootstrap() ( still removing the $application->run() ):
$front = Zend_Controller_Front::getInstance();
// You can put more here if you use non-default modules
$front->setControllerDirectory(array(
'default' => APPLICATION_PATH.'/controllers'
));
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setNeverRender(true);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
$req = new Zend_Controller_Request_Http("http://anydomain.tld/controller/action");
// Example just to see how this can be extended
$req->setParam("someVar", "someValue");
$front->setRequest($req);
$front->dispatch();
In the end you have a isolated PHP file that bootstraps everything the same as your main index.php for the web, but you can manually trigger a controller/action as needed, giving you easier access to the rest of the files with how ZF1 intended you to access them.
Controllers are designed to be used in an MVC, not by scripts. Your controller should assemble request variables, direct them to models and return an HTTP response of some sort. Your scripts should act directly on the models instead.
Anyhow, if you insist, you can instantiate a controller class and call methods just like any other class as long as you inject any dependencies that the MVC would have.
If you want logic used in multiple places in your actions, then it should go in an action helper or if very generic code, then in a custom library (/library/custom/)
NB: The authentication would be better suited in a plugin rather than the pre-dispatch method in every controller.
You should not have to call a controller action for this, your logic should reside in your models. Then you can create a new instance of your model and invoke the appropriate methods. example :
require_once '/path/to/mymodel.php';
$mymodel = new Mymodel();
$data = $mymodele->fetchAll();
PS: Maybe you should think of creating a restful api to handle calls from outside your application
UPDATE:
ok, I see now what you need, The best way to achieve it is to call a url instead of a file (e.g. website.com/emails/send), if you are worried about security you can use some preshared key to make sure the request comes from you, send it with the request and check if it's correct in your action.
I have a class...
class myclass {}
$myclass = new myclass();
$myclass->frigin = 'awesome';
Later on in a different PHP file I have some includes...
include('hippie_deflectors.php');
However the PHP in that includes does not see $myclass at all.
What is the simplest way to make PHP obey?
This file...
.com/[module]/requested_page.php
...has two includes which filter down the following top-to-bottom...
Includes set 1
.com/system/header.php
.com/system/header_classes.php [$myclass is defined here]
Includes set 2
.com/[module]/index_get.php
.com/system/template_1.php
.com/system/includes_js.php
.com/system/scripts/onload.js [$myclass undefined here]
Your question is a bit to comprehend. But this will work:
File: File1.php
class myclass {}
$myclass->frigin = 'awesome';
include('hippie_deflectors.php');
File: hippie_deflectors.php
include('different_file.php');
File: different_file.php
var_dump($myclass);
will print:
object(stdClass)#1 (1) { ["frigin"]=> string(7) "awesome" }
Is this the setup you are having?
I realized my mistake which hopefully someone else will learn from. While I have had issues of scope (a PHP file including another and then only being able to access a class by passing it as a parameter to a function) what I ended up realizing was that the JavaScript file was being output as a string, not as an includes! That means that the JavaScript file would make the browser make a second request of which only that file would be parsed by PHP.
Visually...
Client Request [JavaScript file output in string for script element]
Client receives page result.
Client requests script file.
Script file parsed by PHP on second/separate request.
Thankfully since I program things to be highly modular I was able to declare the class, create a new copy of it and then include a modular PHP file that doesn't include the entire class but a smaller though more universal chunk of variables that I needed.
This does not resolve the separate though related issue where classes are only accessible in X number of includes before you have to pass them as parameters to functions.