-1

My question is how to dynamically include and call the model and view classes in a simple MVC model? I have no problem calling the controller, I have found various ways to do that, but I can't find a good solution for calling and passing in the model and view.

I have setup a .htaccess file to read the url as "www.domain.com/controller/method/id".

I was previously trying to do a check if a file exists for the model and view the same way I am doing the controller using the $cont variable, and then trying to load the model and pass it into the controller, then the view. The issue I had is that all the includes are using the $cont variable to call instantiate their classes and could not tell each other apart. I tried adding a suffic $cont . 'Controller', but then I couldn't load the class at all, let alone pass in the model or view.

Here is my latest example without model or view.

    <?php

//===============================================
// Debug
//===============================================
ini_set('display_errors','On');
error_reporting(E_ALL);

//===============================================
// Includes
//===============================================
require('coremvc.php');

//===============================================
// Constants & Globals
//===============================================
define('BASE_PATH', dirname(realpath(__FILE__)));
$GLOBALS['var'] = "";

//===============================================
// Session
//===============================================
session_start();

//===============================================
// Router
//===============================================

if ($_SERVER['REQUEST_URI'] !== '/') {
  $uri = $_SERVER['REQUEST_URI'];
  $uri = ltrim($uri, '/');
  $request = explode('/', $uri);

  foreach ($request as $key => $val) {
    if(empty($request[$key])) {
      unset($request[$key]);
    }
  }

  $request = array_values($request);

  if (isset($request[0])) { 
    $cont = $request[0];
  }

  if (isset($request[1])) { 
    $action = $request[1];
  }

} else {
  $cont = "home";
}

if (FILE_EXISTS('/controllers/' . $cont . 'Controller.php')) {
  require '/controllers/' . $cont . 'Controller.php';
} else {
  $cont = "home";
  require '/controllers/homeController.php';
}

//===============================================
// Start the controller
//===============================================
$controller = new $cont;

I have made the following changes to the example above, posted it below, as well as my super easy bake oven simple controller.

<?php

if (FILE_EXISTS('/controllers/' . $cont . 'Controller.php')) {
  require '/controllers/' . $cont . 'Controller.php';
} else {
  $cont = "home";
  $cont = ucfirst($cont) . 'Controller';
  require '/controllers/homeController.php';
}

//===============================================
// Start the controller
//===============================================
$controller = new  $cont('World');
$controller->world();

Controller, it is just extending an empty class which I was thinking I could use if I wanted to extend a common method to every class. That is what the coremvc.php is in the index.php above.

<?php

Class HomeController extends Controller
{

  function __construct($world) {
    echo "Hello ";
    $this->world = $world;
  }

  function world() {
    echo $this->world;
  }
}
6
  • 1
    Isn't inside the controller to call the Model and View ? You're showing only the 'route'. Edit: This example of MVC may be helpful An example of an MVC controller
    – Debflav
    Aug 29, 2014 at 18:34
  • I will take a look in a moment, ty for the link. I was trying to replicate a different mvc model I saw which instantiated the classes from the routers. $model = new Model; $controller = new Controller(model); $view = new View($controller, $model);
    – Just A Guy
    Aug 29, 2014 at 18:38
  • When you added the suffix, did you actually change the class names of the controllers? That would work completely fine. Aug 29, 2014 at 18:39
  • Actually, it's hard without the whole tree of your app. What's the name of your controller ? home or homeController ?
    – Debflav
    Aug 29, 2014 at 18:50
  • I just updated my post with some updated code and the controller I am using for testing. It seems to be working as is, very messy so I will clean it up, but I think I should be able to use this with the model and view as well. Please if any of you have any better suggestions to this method I am all ears and eyes.
    – Just A Guy
    Aug 29, 2014 at 18:59

2 Answers 2

2

You want to load and call classes easily. I dynamically load classes that end in ".class.php". This makes things easy for me.

I put this in my index.php... where /app/ is where I have my php classes:

<?php
define('CLASS_DIR', '/app/');
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . CLASS_DIR);
spl_autoload_extensions('.class.php');
spl_autoload_register();

Next, I require my routes:

require 'rte/myroute.php';

I let my routes (controllers) direct my traffic to my models, albeit some parsing, etc.

I typically develop REST based APIs in PHP, so the "view" is just a JSON response.

The HTML / JavaScript client consumes the responses.

A good framework that I like is SlimPHP. I load it up using Composer.

http://www.slimframework.com/

https://getcomposer.org/

Here's an example of calling a class as an instance and statically, since you auto-loaded, you don't need to include anything at the top:

<?php
$param1 = 1;
$param2 = 2;
MyClass::myFunc($param1);
$myObj = new MyClass;
$myObj->myFunc2($param2);
0

As it is already say you can have a look to use the spl_autoload_register which will require all your files in the given path. You can change this function to improve the load.

Concerning the Model with your current code you can implement it as follow:

$controllerPath = "/controllers/{$cont}Controller.php";
$modelPath = "/model/{$cont}Model.php";
if (FILE_EXISTS($controllerPath)) {
  require $controllerPath;
  if (FILE_EXISTS($modelPath)) {
      require $modelPath;
  }
  else {
      throw new \LogicException(
          sprintf("Your controller must implement a model. No model found: %s", $modelPath)
      );
  }
} else {
  $cont = "home";
  require "/controllers/{$cont}Controller.php";
  require "/model/{$cont}Model.php";
}

//===============================================
// Start the controller
//===============================================
$controller = new $cont($cont);

In this sample of code, $cont is the name of the page like home. Which require the homeController and homeModel. Then in your __construct($modelName) just set the model.

However, I don't recommand you tu use this because your controller can load many Models. Then, your controller could look like this:

<?php
namespace \App\Controller; // If you use namespace

use App\Model\homeModel, // If you use namespace
    App\Model\productModel; // If you use namespace

Class HomeController extends Controller
{

  private $model;

  /* If this function is common to all controllers just move it 
  in the parent Controller class( one more time, I don't recommend to set
  the model using this way). */
  public function __construct($model) {
    $this->model= $model;
  }

  public function login() {
    $homeModel = new homeModel(); // If you use namespace

    // Example to call the view
    $myValue = 'Hello world';
    $this->render(array("myVariableName" => $myValue))
  }
}

In this second example $this->render can be a method in your Controller class (which by the way should be an abstract class). I'll give a last sample of code for the logic of the abstract controller.

<?php

namespace \App\Controller;

abstract class AbstractController {

    /* Common code for all controllers */
    public function __construct() {

    }

    /* View renderer */
    protected function render($parameters) {
      /* Call the view here maybe an another class which manage the View*/
    }
}

To conclude, you can implement this MVC in many way, this code is just a suggestion and maybe its not the best way. I advise you to have a look with the spl_autoload that I put at the beginning of my answer.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.