如何在简单的php mvc示例中包含模型/视图和调用类

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;
  }
}
php
doumen6605
doumen6605 您可能会觉得这很有用:stackoverflow.com/a/19309893/727208另外,作为提示:您所谓的“视图”只是一个模板。而模特不是一个阶级。
大约 6 年之前 回复
dqk77945
dqk77945 我刚刚用一些更新的代码和我用于测试的控制器更新了我的帖子。它似乎按原样运行,非常凌乱所以我会清理它,但我想我应该能够将它与模型和视图一起使用。如果你们中的任何一个人对这种方法有任何更好的建议,我都是耳朵和眼睛。
大约 6 年之前 回复
doubi7306
doubi7306 实际上,没有应用程序的整个树,这很难。控制器的名称是什么?家庭或家庭控制器?
大约 6 年之前 回复
dongli7236
dongli7236 添加后缀后,您是否真的更改了控制器的类名?这将完全正常。
大约 6 年之前 回复
douxian9706
douxian9706 我将在片刻中看一下这个链接。我试图复制我看到的另一个mvc模型,它从路由器中实例化了类。$model=newModel;$controller=newController(model);$view=newView($controller,$model);
大约 6 年之前 回复
duanfu3884
duanfu3884 是不是在控制器里面调用Model和View?你只显示'路线'。编辑:这个MVC的例子可能有用MVC控制器的一个例子
大约 6 年之前 回复

2个回答

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.

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);
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐