请知悉:本文最近一次更新为 7年 前,文中内容可能已经过时。

本节对应书里第二章 Using the router component in a module
原文翻译整理如下:

本节,我们将展示为应用创建路由。为了这么做,需要进入config配置的目录,并创建包含以下代码的routing.php文件:

<?php
$di['router'] = function() use ($default_module, $modules, $di,
$config) {
$router = new PhalconMvcRouter(false);
$router->clear();
$moduleRouting = __DIR__.'/.apps/'.ucfirst($default_module).'/
config/routing.php';
if (file_exists($moduleRouting) && is_file($moduleRouting)) {
$router = include $moduleRouting;
} else {
$router->add('#^/(|/)$#', array(
'module' => $default_module,
'controller' => 'index',
'action' => 'index',
));
$router->add('#^/([a-zA-Z0-9_]+)[/]{0,1}$#', array(
'module' => $default_module,
'controller' => 1,
));
$router->add('#^/{0,1}([a-zA-Z0-9_]+)/([a-zA-Z0-9_]+)
(/.*)*$#', array(
'module' => $default_module,
'controller' => 1,
'action' => 2,
'params' => 3,
));
}
return $router;
};

这个文件中,我们使用了PhalconMvcRouter组件。我们检查是否有路由信息匹配对应的模块,如果存在则载入;否则,我们建立默认的路由规则。如果你从头一直跟着书中内容执行的话,现在你应该有如下的目录结构了:

├── cache
├── composer.json
├── composer.lock
├── composer.phar
├── config
│ ├── config.php
│ ├── loader.php
│ ├── routing.php
│ └── services.php
├── index.php
├── logs
├── modules
│ ├── Api
│ ├── Backoffice
│ ├── Bootstrap.php
│ ├── Core
│ └── Frontend
├── public
│ └── index.php
└── vendor
├── autoload.php
├── composer
├── phalcon
└── swiftmailer

在第一章,我们已经创建了网站的配置文件和域名。为了生效,我们在hosts中加入了www.learning-phalcon.localhost到127.0.0.1的解析。现在在浏览器访问https://learning-phalcon.localhost:

请使用https://协议访问,在Chrome可能出现访问失败的情况,因为根域名并没有注册成为顶级域名。(了然:这句没啥意义)

如果你访问了刚才的地址,你应该看到如下截图的报错信息:

让我们通过建立Frontend模块的文件来修正这个错误。进入modules/Frontend目录,建立名为Module.php的文件,内容如下:

<?php
namespace AppFrontend;
use PhalconMvcModuleDefinitionInterface;
class Module implements ModuleDefinitionInterface
{
/**
* Registers the module auto-loader
*/
public function registerAutoloaders(PhalconDiInterface $di = null) {}
/**
* Registers the module-only services
*
* @param PhalconDI $di
*/
public function registerServices(PhalconDiInterface $di)
{
$config = include __DIR__ . "/Config/config.php";
$di['config'] = $config;
include __DIR__ . "/Config/services.php";
}
}

现在,将这个文件拷贝到每个模块的目录并修改命名空间。比如,在Api模块目录的命名空间应该是AppApi。现在,你的模块目录应该如下结构:

├── Api
│ ├── Module.php
├── Backoffice
│ ├── Module.php
├── Core
│ ├── Module.php
├── Frontend
│ ├── Module.php
├── Bootstrap.php

如您从本文得到了有价值的信息或帮助,请考虑扫描文末二维码捐赠和鼓励。

尊重他人劳动成果。转载请务必附上原文链接,我将感激不尽。


与《零基础学Phalcon 22 在模块中使用路由组件 一》相关的博文:


留言

avatar
😀
😀😁😂😅😭🤭😋😘🤔😰😱🤪💪👍👎🤝🌹👌