首页 > 解决方案 > MVC indexController 未使用正确的操作

问题描述

我的 IndexController 中有两个操作。

public function indexAction()
{
    $this->view->setVars([
        'name' => 'Stefan',
    ]);
}

public function testAction()
{
    $this->view->setVars([
        'name' => 'testOutput',
    ]);
}

当要调用我的索引页时

https://localhost/index/

它确实输出了我在我的 views/index/index.php

<h1>Hello <?php echo $name ?></h1>

我确实得到了输出

你好斯特凡

问题:

如果我必须

https://localhost/index/test

即使我清楚地在我的testAction

因此,indexAction即使我没有在我的浏览器中调用操作,他也可以访问。

我想要的是,因为我echo $name;在我的 test.php 文件中有。

我得到输出

测试输出

这将是我的自动加载器。

先感谢您。

    <?php
// simple autoloader
spl_autoload_register(function ($className) {
    if (substr($className, 0, 4) !== 'Mvc\\') {
        // not our business
        return;
    }
    $fileName = __DIR__.'/'.str_replace('\\', DIRECTORY_SEPARATOR, substr($className, 4)).'.php';
    if (file_exists($fileName)) {
        include $fileName;
    }
});
// get the requested url
$url      = (isset($_GET['_url']) ? $_GET['_url'] : '');
$urlParts = explode('/', $url);
// build the controller class
$controllerName      = (isset($urlParts[0]) && $urlParts[0] ? $urlParts[0] : 'index');
$controllerClassName = '\\Mvc\\Controller\\'.ucfirst($controllerName).'Controller';
// build the action method
$actionName       = (isset($urlParts[1]) && $urlParts[1] ? $urlParts[1] : 'index');
$actionMethodName = $actionName.'Action';



try {
    if (!class_exists($controllerClassName)) {
        throw new \Mvc\Library\NotFoundException();
    }
    $controller = new $controllerClassName();
    if (!$controller instanceof \Mvc\Controller\Controller || !method_exists($controller, $actionMethodName)) {
        throw new \Mvc\Library\NotFoundException();
    }
    $view = new \Mvc\Library\View(__DIR__.DIRECTORY_SEPARATOR.'views', $controllerName, $actionName);
    $controller->setView($view);
    $controller->$actionMethodName();
    $view->render();
} catch (\Mvc\Library\NotFoundException $e) {
    http_response_code(404);
    echo 'Page not found: '.$controllerClassName.'::'.$actionMethodName;
} catch (\Exception $e) {
    http_response_code(500);
    echo 'Exception: <b>'.$e->getMessage().'</b><br><pre>'.$e->getTraceAsString().'</pre>';
}

编辑:

我在索引后调用的操作真的无关紧要。它可以是索引/asdsad

而且他还是去了主要的indexAction。

它甚至没有说他找不到动作。

编辑2:

输出自var_dump($url,$urlParts,$controllerName,$actionMethodName)

    string(0) ""
array(1) {
  [0]=>
  string(0) ""
}
string(5) "index"
string(11) "indexAction"

标签: phpmodel-view-controllerautoload

解决方案


推荐阅读