php - MVC indexController 未使用正确的操作
问题描述
我的 IndexController 中有两个操作。
public function indexAction()
{
$this->view->setVars([
'name' => 'Stefan',
]);
}
public function testAction()
{
$this->view->setVars([
'name' => 'testOutput',
]);
}
当要调用我的索引页时
它确实输出了我在我的 views/index/index.php
<h1>Hello <?php echo $name ?></h1>
我确实得到了输出
你好斯特凡
问题:
如果我必须
即使我清楚地在我的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"
解决方案
推荐阅读
- php - 上传后个人资料图片未在浏览器中更新
- java - Java HTTP 连接似乎保持打开状态
- sql - SQL - 仅从表中获取并非所有值都是空值的列
- javascript - 浏览器上的图像处理
- angular - Angular:复选框的表单组绑定在迁移到版本 6 后未设置默认值
- php - 如果输出被过滤,则 bash 脚本的 php 实时输出
- r - 避免评估错误:R SF 包中的 TopologyException 错误
- python - AttributeError:“迈克尔”对象没有属性“_class_”
- java - Itext pdf - 文本向右对齐
- pycharm - Pycharm 运行外部工具宏