Yii 框架中控制器通过目录和命名空间实例化
Yii 框架支持模块以及控制器目录中的子目录,因此某些特定操作的路径可以是
/index.php?r=module/controller/action
或/index.php?r=subdirectoryInControllerDir /控制器/操作
。
我的目标是在控制器目录中有多个子目录。在这些文件夹中,我将使用命名空间创建与父级同名的控制器。
但是,如果我写
namespace mynamespace;
class MyController extends \MyController {
}
Yii 会加载 MyController
而不是 mynamespace\MyController;
这里有什么建议吗?
Yii framework supports modules and also subdirectories in controllers directory, so path to some specific action could be
/index.php?r=module/controller/action
or/index.php?r=subdirectoryInControllerDir/controller/action
.
My goal here is to have multiple subdirectories in the controllers directory. Inside these folders I would create controllers with the same names as parent ones using namespaces.
However if I write
namespace mynamespace;
class MyController extends \MyController {
}
Yii would load MyController
instead of mynamespace\MyController;
Any suggestions here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Yii 对命名空间使用直观的命名约定,它从 \application 开始,并且必须遵循物理目录结构,就像内置的自动加载配置一样。
如果您的 MyController 基类位于 protected/controllers/ 中,那么它应该使用命名空间 application\controllers;
和 protected/controllers/subdir/ 中的子 MyController
来发出类似“subdir/my”的请求,您需要在包含类文件后立即将以下代码添加到
CWebApplication::createController()
(或在子类中继承它):如果您设置了
controllerNameSpace
对于CWebApplication
,您还可以使用该值而不是硬编码\\application\\controllers\\
。Yii uses an intuitive naming convention for namespaces, which starts from \application and must follow the physical directory structure, like the built-in autoload config.
If your base MyController class is in protected/controllers/, then it should use
namespace application\controllers;
and the child MyController in protected/controllers/subdir/
To make a request like "subdir/my" work, you need to add the following code to
CWebApplication::createController()
(or inherit it in a subclass) right after the class file is included:If you have set
controllerNameSpace
ofCWebApplication
you can also use that value instead of hardcoding\\application\\controllers\\
.