Trying to learn PHP MVC. So far so good until this moment. I have function like this in my ./controllers/index.php
<?php
class Index extends Controller {
function __construct() {
parent::__construct();
}
function showFeeds() {
return 'done';
}
}
?>
I know how to call model class and run showFeed() on model class. my problem is how to print 'done' on my ./views/index.php. what are the options for that.
I already tried some of them listed below. but no luck.
Finally I fixed my problem
PAGE: /controllers/index.php
<?php
class Index extends Controller {
function __construct () {
parent::__construct ();
}
function showFeeds () {
return 'done';
}
}
?>
PAGE: ./views/index/index.php
<?php
$_index = new Index ();
$params = $_index -> showFeeds ();
?>
You're best off using a PHP Framework for MVC
A few frameworks are:
Codeigniter, Zend and CakePHP
These frameworks use MVC with their own syntax so it's really simple to use. I personally use Codeigniter, and it's fairly easy
For example, in codeigniter you can do this:
Controller:
function showFeed(){
$data['done'] = 'Done';
$this->load->view('yourview', $data);
}
View:
<?php echo $done; ?>
In MVC, generally speaking the controller should deal with the model, get a view, set the view's data and then invoke the view or return it to render the view.
What you are trying to do is call back to the controller from the view. I suggest moving showFeeds()
into the model. In the controller, call the model to get the result of showFeeds()
and pass the value to the view, and finally invoke the view for rendering.
In general, your controller will generate the view. To be generated, the view will need arguments which are often the datas to show.
For example with a HelloWorld controller, the conception would look like this:
class HelloWorldController extends Controller {
function indexAction($name) { // The index page of your site for example
return $this->getView()->render('helloworld.html', array('name' => $name))
}
}
Then in your view you will print something like "Hello " . $name which is the name you passed in the render function.