m.S*_*rto 3 php model-view-controller routes class
我想知道是否可以在 php 中创建一个 mvc 项目而不使用路由。例如:
我有控制器 strumenti.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');
}
}
Run Code Online (Sandbox Code Playgroud)
和我的模型 struentimodel.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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个视图(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>
Run Code Online (Sandbox Code Playgroud)
如果我从控制器调用模型,即使没有路由也没有问题,但是我可以在没有路由的情况下从视图调用控制器吗?
在我的示例中,我通过链接这样称呼它:
<a href="<?php echo mysite/strumenti/deleteStrumento/' . $strumenti[$riga][0]; ?>">x</a>
Run Code Online (Sandbox Code Playgroud)
结构为:类/方法/参数
是否可以在没有路由的情况下调用类方法?
“路由”与 MVC 没有什么特别的关系。通俗地理解,“路由”是一些将URL解析为可执行代码(通常是控制器)的函数/类/代码。好吧,您可以通过使用类似 的 URL 来“免费”使用 PHP 的标准行为/controllers/foo-controller.php
,其中包含将执行控制器的代码。您的控制器甚至不需要是一个类,它只需要是接收请求并可以决定调用哪些模型操作和/或发送哪些视图/响应的东西。
这就是 MVC 的全部内容:拥有一个包含应用程序可以“执行”的所有内容的核心模型,拥有与为模型提供 UI 的视图分开的视图,最后拥有一个作用于用户输入(此处:HTTP 请求)的控制器。这种分离只是为了让您可以通过交换 UI(视图)和输入处理程序(控制器)来轻松地使您的应用程序(模型)适应不同的场景。其中没有规定类、路由或其他任何东西的使用。