Ok so I have some gaps in my understanding of PHP OOP, classes and functions specifically, this whole construc开发者_开发技巧tor class deal. I use both Zend and CI but right now Im trying to figure this out in CI as it is less complicated.
So all Im trying to do is understand how to call a function from a view page in code igniter. I understand that might go against MVC but Im working with an api and search results not from my database, so basically, I want to define a function in my class that I am able to call in one of my view pages.. and I keep getting "Fatal error: Call to undefined function functionname" error no matter what I try.
I thought I just had to declare
public function testing() {
echo "testing testing 123;
}
but calling that from the view I get that error. Then I read something about having to go parent::Controller();
in the index of the class where the testing function also resides? But that didnt work either. Anyways, ya, can someone explain what I need to do in order to call the "testing()" function on one of my view pages? and clarification on the constructor class and what exactly parent::Controller() even does, would be much appreciated as well.
Like you said, that goes against the concept of MVC, so a better bet would be to use a helper function instead of declaring it as a controller method. Or, even better, let your controller deal with all the search API stuff, then pass the search results from your controller to your view.
I agree with both those points, but there are instances where you don't get the data you need until the view has been loaded (e.g. like some php data inside inline javascript or something).
If that's the case, I'd use an ajax call (within the view) to hit a function in the controller (since you just need a url to call them) and send along post data if the function needs to be fed anything. Does that make sense?
Yeah, like you said, that goes against the concept of MVC, but nothing is impossible. We can make it simply and follow the CI concept. You just need to pass a Controller object to the view:
class Test extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function sayhi() {
echo "Hi from controller...";
}
public function index() {
$this->load->view('test', array('controller' => $this));
}
}
Then you can call function defined at the controller, for example I called sayhi()
from my view page:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h2>
<?= $controller->sayhi() ?>
</h2>
</body>
</html>
精彩评论