我有这个错误(在 silex 2.0 下):
UndefinedFunctionException in app.php line 88: Attempted to call function "postIndexArticle" from namespace "SocialWall\Controller".
in app.php line 88
at {closure}(object(Application)) in Container.php line 113
at Container->offsetGet('home.controller') in CallbackResolver.php line 55
at CallbackResolver->convertCallback('home.controller') in ServiceControllerResolver.php line 50
at ServiceControllerResolver->getController(object(Request)) in HttpKernel.php line 136
at HttpKernel->handleRaw(object(Request), '1') in HttpKernel.php line 68
at HttpKernel->handle(object(Request), '1', true) in Application.php line 496
at Application->handle(object(Request)) in Application.php line 477
at Application->run() in index.php line 17
我的 app.php
<?php
use SocialWall\Controller;
$app['home.controller'] = function($app) {
return SocialWall\Controller\postIndexArticle($app);
};
我的路由.php
<?php
// Home page
$app->get('/', 'home.controller')->bind('home');
HomeController.php
<?php
namespace SocialWall\Controller;
use Silex\Application;
use SocialWall\DAO\ArticleDAO;
function postIndexArticle(Application $app) {
return function() use ($app) {
return new $app['twig']->render('index.html.twig', array('articles' => $app['dao.article']->findAll()));
};
}
我需要帮助!
最佳答案
我试图重新创建您的演示,它对我有用。我看到您正在关注此处显示的最后一个示例 http://silex.sensiolabs.org/doc/master/providers/service_controller.html提到使用可调用对象作为 Controller :
// app.php
<?php
require_once __DIR__.'/vendor/autoload.php';
require_once 'HomeController.php';
$app = new Silex\Application();
$app['debug'] = true;
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
$app->register(new Silex\Provider\TwigServiceProvider());
$app['home.controller'] = function($app) {
return \SocialWall\Controller\postIndexArticle($app);
};
// Home page
$app->get('/', 'home.controller')->bind('home');
$app->run();
然后 Controller 在一个单独的文件中:
// HomeController.php
namespace SocialWall\Controller;
use Silex\Application;
function postIndexArticle(Application $app) {
return function() use ($app) {
return $app['twig']->createTemplate('test template')->render([]);
};
}
这只打印测试模板
。
所以我认为问题出在这些事情之一(或可能两者):
您的
postIndexArticle
的内部可调用返回return new $app['twig']->render(...
这是不正确的。你不不想在这里使用关键字new
,因为render()
方法只返回字符串模板。我认为您要调用的
app.php
或HomeController.php
中的命名空间有问题$app['home.controller'] = function($app) { return SocialWall\Controller\postIndexArticle($app); };
所以尝试使用绝对命名空间路径,就像我对
\SocialWall\Controller\postInd...
所做的那样
关于php - UndefinedFunctionException 试图从命名空间 xxx 调用函数 xxx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39574190/