CakePHP 2.0.4:使用“数字”控制器中的助手
我知道在控制器中使用助手是违反 MVC 方法的,但在某些情况下它是有用的。例如,考虑我的 CakePHP 1.3.13 项目之一中处理图像上传的控制器代码片段:
elseif ($_FILES['data']['error']['ModelName']['field_name'] === UPLOAD_ERR_INI_SIZE) {
App::import('Helper', 'Number');
$Number = new NumberHelper();
$this->Session->setFlash("The image you uploaded was not saved because it appeared to be larger than {$Number->toReadableSize($max_filesize_in_bytes)}.");
}
我现在正在开发 CakePHP 2.0.4 项目,并且使用了相同的代码,只是替换了 App ::import('Helper', 'Number');
与 App::uses('NumberHelper', 'View/Helper');
,我收到此错误消息:
Warning (4096): Argument 1 passed to Helper::__construct() must be an instance of View, none given, called in /Path/To/My/Website/app/Controller/MyController.php
Any想法?
I know it's against MVC methodologies to use helpers in controllers, but there are some cases where it's useful. For example, consider this snippet of controller code from one of my CakePHP 1.3.13 projects that handles an image upload:
elseif ($_FILES['data']['error']['ModelName']['field_name'] === UPLOAD_ERR_INI_SIZE) {
App::import('Helper', 'Number');
$Number = new NumberHelper();
$this->Session->setFlash("The image you uploaded was not saved because it appeared to be larger than {$Number->toReadableSize($max_filesize_in_bytes)}.");
}
I'm working on a CakePHP 2.0.4 project now and I used the same code, except I replaced App::import('Helper', 'Number');
with App::uses('NumberHelper', 'View/Helper');
and I got this error message:
Warning (4096): Argument 1 passed to Helper::__construct() must be an instance of View, none given, called in /Path/To/My/Website/app/Controller/MyController.php
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不应该在控制器中使用助手。我很久以前就提议应该为此设立图书馆课程。希望这将被集成到 2.1 中
,在那之前你应该使用
you shouldnt use helpers in controllers. I proposed quite some time ago that there should be library classes for this. hopefully this will be integrated in 2.1
until then you should be using
我知道已经晚了,但 Cake Core 团队已在核心库中嵌入了
CakeNumber
类。从现在开始,我们应该在控制器/模型中直接使用下面的函数,而不是创建helper
对象。更多有用的函数列表请参见
CakeNumber
类并查看核心库的完整列表,请访问Core库
。我希望它可以帮助某人。
I know it is late but Cake Core team had embedded
CakeNumber
Class in core library. From now onwards we should use directly below functions in our controller / model instead creating an object ofhelper
.For more useful functions list please see
CakeNumber
class and to see complete list of core libraries please visitCore Libraries
.I hope it may help some one.