我想知道是否可以在不使用路由的情况下在 php 中创建一个 mvc 项目。 例如:
我有 Controller stumenti.php
class Strumenti
{
public function index()
{
require 'application/models/strumentimodel.php';
$strumenti_model=new StrumentiModel("r");
$strumenti = $strumenti_model->getAllInstruments();
require 'application/views/_templates/header.php';
require 'application/views/strumenti/index.php';
require 'application/views/_templates/footer.php';
}
public function deleteStrumento($nome)
{
if (isset($nome)) {
require 'application/models/strumentimodel.php';
$strumenti_model=new StrumentiModel("r");
$strum=$strumenti_model->deleteStrumentoDaArray($nome);
}
header('location: 'mysite/strumenti/index');
}
}
和我的模型 strumentimodel.php
class StrumentiModel
{
private $handle;
function __construct($mode) {
try {
$this->handle = fopen(STRUMENTI, "$mode");
} catch (PDOException $e) {
exit('Errore di apertura file');
}
}
public function getAllInstruments()
{
$csv = array();
$lines = file(STRUMENTI);
foreach ($lines as $key => $value)
{
$csv[$key] = str_getcsv($value,";");
}
return $csv;
}
public function deleteStrumentoDaArray($nome)
{
//array con tutti gli strumenti
$strum=$this->getAllInstruments();
for($i=0;$i<count($strum);$i++){
if(in_array($nome,$strum[$i])){
$this->indice=$i;
}
}
unset($strum[$this->indice]);
return $strum;
}
}
这是一个 View (index.php)
<div>
<h3>Strumenti</h3>
<table>
<tr>
<td>nome</td>
<td>modello</td>
<td>tipo</td>
<td>costo</td>
<td>Elimina</td>
<td>Modifica</td>
</tr>
<tbody>
<?php for ($riga=1;$riga<count($strumenti);$riga++): ?>
<tr>
<?php for ($colonna=0; $colonna<count(current($strumenti)); $colonna++): ?>
<td><?php echo $strumenti[$riga][$colonna];?></td>
<?php endfor; ?>
<td><a href="<?php echo mysite/strumenti/deleteStrumento/' . $strumenti[$riga][0]; ?>">x</a></td>
<td><a href="<?php echo mysite/strumenti/index ?>">Index</a></td>
</tr>
<?php endfor; ?>
</tbody>
</table>
</div>
如果我从 Controller 中调用模型,即使没有路由也没有问题,但是我可以在没有路由的情况下从 View 中调用 Controller 吗?
在我的示例中,我通过链接这样调用它:
<a href="<?php echo mysite/strumenti/deleteStrumento/' . $strumenti[$riga][0]; ?>">x</a>
结构是:类/方法/参数
是否可以在没有路由的情况下调用类方法?
最佳答案
“路由”与 MVC 没有特别的关系。通俗地理解的“路由”是将 URL 解析为可执行代码段(通常是 Controller )的一些函数/类/代码。好吧,您可以通过使用像 /controllers/foo-controller.php
这样的 URL 来“免费”使用 PHP 的标准行为,其中包含将执行 Controller 的代码。您的 Controller 甚至不需要是一个类,它只需要是接收请求并可以决定调用哪些模型操作和/或发送哪些 View /响应的东西。
这就是 MVC 的全部意义所在:拥有一个核心模型,其中包含您的应用可以“做”的所有事情,将 View 与为您的模型提供 UI 的 View 分开,最后还有一个 Controller ,它作用于用户输入(此处:HTTP 请求)。这种分离很简单,因此您可以通过交换 UI( View )和输入处理程序( Controller )轻松地使您的应用程序(模型)适应不同的场景。其中没有规定使用类、路由或其他任何内容。
关于没有路由的 PHP MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48183466/