如何在cakephp 2中调用路由(routes.php)文件中的内联函数


How to call inline function from routing (routes.php) file in cakephp 2?

我想调用一个定义在routes.php文件中的内联函数。

我试过这些代码:

Router::connect('/test', function () {    return 'test';exit;});
Router::connect('/test', function () {    echo 'test';exit;});

但是当我访问localhost/cakephp/test时,我得到错误:

 Error: Cannot use object of type Closure as array
File: /var/www/html/massmobile/lib/Cake/Routing/Router.php
Line: 348
Notice: If you want to customize this error message, create app/View/Errors/fatal_error.ctp

在laravel (http://www.tutorialspoint.com/laravel/laravel_routing.htm)中我们可以从路由文件中调用内联函数。有可能在cakephp中做同样的事情吗?

是否可以在cakephp中做同样的事情?

可以,但不是在CakePHP2。

CakePHP3使用。请参阅文档中的路由部分。如果你读过Cake2的API和/或文档,它也会告诉你不能传递闭包。

结论:提高你的文档阅读能力。对于此类问题,没有比快速查看API文档或代码中的方法签名本身更简单的解决方案了。它会告诉你可以传递哪些参数。

我还建议你了解CakePHP是如何工作的,而不是像其他框架的API那样尝试使用它的API。这是行不通的,这种假设也太天真了。它们有不同的方法(简化:约定优于配置vs配置优于约定),它们的API 不同。