PHP MVC Call Controller Function From View

17,466

Solution 1

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 ();
?>

Solution 2

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; ?>
Share:
17,466
AmilaDG
Author by

AmilaDG

Updated on June 05, 2022

Comments

  • AmilaDG
    AmilaDG almost 2 years

    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.

    1. parent::showFeeds()
    2. $this->controller->showFeeds();
  • AmilaDG
    AmilaDG over 10 years
    Really appreciate your help but it gives me this error. Fatal error: Call to a member function showFeeds() on a non-object in C:\xampp\htdocs\framework\views\index\index.php on line 23
  • Kees Sonnema
    Kees Sonnema over 10 years
    That error is given when there's no model called showFeeds(). Make a model function called showFeeds and the error is gone.