Catalyst 中的实用程序 (Perl)
我应该在 Catalyst 项目中的何处放置诸如 sum_it_all()
之类的函数?
它不是一个模型,与数据无关,它不是一个控制器,因为它不询问网络请求。这只是一个简单的功能,我希望它可以在我的所有控制器中访问。
现在我使用 Model/Utils.pm 和 $c->model("utils")->sum_it_all()
,但这似乎真的很荒谬。
Where should I place functions like, for example, sum_it_all()
in Catalyst project?
It's not a model, that's nothing about data, it's not a controller because it doesn't ask the web-request. It's just a simple function and I want it to be accessible in all my controllers.
Now I use Model/Utils.pm and $c->model("utils")->sum_it_all()
, but it seems to be really ridiculous.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您需要在 Catalyst 控制器中使用此功能,只需将其嵌入到您需要的控制器中即可。如果您需要在多个Controller中实现相同的功能。创建一个包含所有功能的新模块。如果您的项目名为“Foo”,则创建例如“Foo::Helpers”。
在每个需要助手提供某些功能的控制器中,只需导入它们“use Foo::Helper qw(sum)”
看看 Sub::Exporter 用于导出函数。
If you need this functions in a Catalyst Controller, just embed it in the controller where you need it. If you need the same function in several Controller. Create a new Module that contains all your functions. If your Project is named "Foo", then create for example "Foo::Helpers".
In every controller where you need some functions from your helper just import them "use Foo::Helper qw(sum)"
Look at Sub::Exporter for exporting functions.
如果它不是 Catalyst 特有的,只需按照 Catalyst 上下文之外的方式使用它即可。我推荐子导出器。
$ctx->model(...)
用于访问层 (::Model::
),该层基本上是 Catalyst 和您的模型之间的“粘合剂”业务/模型逻辑。如果您不需要任何粘合(自动配置和组件膨胀以方便访问是一个常见的用例),您可以像在每个 Perl 应用程序中一样将其抽象出来。If it's nothing Catalyst specific, just use it how you would outside the Catalyst context. I'd recommend Sub-Exporter.
The
$ctx->model(...)
is meant for accessing a layer (::Model::
) that is basically a "glue" between Catalyst and your business/model logic. If you don't need any glue (automatic configuration and component inflation for easier access is a common use-case), you can abstract it away as in every Perl application.我建议您只需添加该功能和其他有用的功能作为 Catalyst 插件
您可以使用语法
$c->sum_it_all()
访问它(请参阅下面的示例插件)========示例自定义插件====
I recommend you simply add that function and other useful ones as a Catalyst Plugin
and you can access it using the syntax
$c->sum_it_all()
(see sample plugin below)========Example custom Plugin====
我在 Utils.pm Helper 包中有一组函数,通过催化剂我想使用 $c->utils 访问器访问所有方法。
例如:
在催化剂中,我想使用
$c->utils->method1()
或$c->utils->method2 调用 method1 ()
请让我知道实现此目的的最佳方法。
I have set of functions in Utils.pm Helper package, through catalyst I want to access all the methods using $c->utils accessor.
For Eg:
In catalyst, I would like to call method1 using
$c->utils->method1(<params>)
or$c->utils->method2(<params>)
Please let me know the best way to accomplish this.