我是Yii 2框架的新手。为了给我的web应用程序结构化,我想把每个控制器放在一个子文件夹中,并为每个子文件夹中的每个动作制作一个单独的控制器。就像那个!
controllers
**User**
IndexController
EditController
UpdateController
**Profile**
IndexController
EditController
UpdateController
在Yii 2里我怎么安排呢。提前谢谢
2条答案
按热度按时间a7qyws3x1#
你的例子是对的。
然后在
IndexController/EditController/UpdateController
中,您有actionIndex
,如果您运行domain.com/user/index
或domain.com/user/edit
,它将在当前控制器中执行actionIndex
(IndexController
或EditController
)lpwwtiir2#
不确定是否有其他更有效的方法,但一个有效的将是以下。
所以,假设我们有一个控制器,我们想把它的一些动作存储到不同的php文件中。
因此,您可以看到,我们有3个外部操作和一个内部操作。
前两个,是框架的工具,用于生成错误页面和验证码,实际上,它们启发了我的答案。
而第三个,则由我们来定义:
因此,我们已经命名了操作,并在一个单独的目录中创建了新的操作类。
最后,我们的观点是:
并看到它的行动:
更新
在发布答案后,我意识到也许你也可以从另一种技术中受益。
如果您想这样做,前面的答案是好的:
Extract actions into individual files
.但是,如果您的应用程序具有一定的大小,也许您应该考虑使用Modules。
您可以手动创建它们或使用Gii生成它们:
生成后,请将其包含在您的配置中:
模块就是这样做的,将应用程序逻辑分组到一个目录、控制器、模型、视图、组件等中。
还有两个提示:
现在要访问您的模块,只需访问
http://www.your-site.local/profile/default/index
,如您所见,它类似于module/controller/action
。如果你想在模块中生成动作的链接,你可以:
同样,如您所见,我们使用
module/controller/action
作为路由。最后,如果你在一个模块中,比如说
profile/picture/edit
,你想从SiteController
链接到Contact页面,你可以这样做:注意路由开头的双斜杠
//
,如果没有它,它将生成指向当前模块profile/site/contact
的url。