我是使用框架和Silex的新手,我试着和Silex合作,写我的第一个项目。
我使用此silex-bootstrap
:https://github.com/fbrandel/silex-boilerplate
现在在我的app/app.php
:
<?php
require __DIR__.'/bootstrap.php';
$app = new Silex'Application();
$app->register(new Silex'Provider'ServiceControllerServiceProvider());
// Twig Extension
$app->register(new Silex'Provider'TwigServiceProvider(), array(
'twig.path' => __DIR__.'/views',
));
// Config Extension
$app->register(new Igorw'Silex'ConfigServiceProvider(__DIR__."/config/config.yml"));
$app->get('/admin', new App'Controller'Admin'AdminDashboard());
return $app;
在app/Controller/Admin/AdminDashboard.php
:中
<?php
namespace App'Controller'Admin;
use Silex'Application;
use Silex'ControllerProviderInterface;
use Silex'ControllerCollection;
class AdminDashboard implements ControllerProviderInterface {
function __construct()
{
return "Dashboard";
}
function index()
{
return "Index Dashboard";
}
public function connect(Application $app)
{
return "OK";
}
}
当我试图访问网站时,我收到了以下错误:http://localhost/project/public
InvalidArgumentException in ControllerResolver.php line 69:
Controller "App'Controller'Admin'AdminDashboard" for URI "/admin" is not callable.
我该怎么办?
您正试图使用控制器提供程序作为实际控制器。这是两件不同的事情。提供商只需在您的silex应用程序中注册控制器。您的提供商应该是这样的:
namespace App'Controller'Admin;
use Silex'Application;
use Silex'ControllerProviderInterface;
class AdminDashboardProvider implements ControllerProviderInterface
{
public function connect(Application $app)
{
$controllers = $app['controllers_factory']();
$controllers->get('/', function() {
return 'Index Dashboard';
});
return $controllers;
}
}
然后,您应该在app/app.php
中将该控制器提供程序安装到您的应用程序中。
$app->mount('/admin', new AdminDashboardProvider());
显然,一旦你有了几个以上的控制器,或者你的控制器变大了,这就不是很优雅了。这就是ServiceControllerServiceProvider
的作用所在。它允许您的控制器是独立的类。我通常使用这样的模式:
<?php
namespace App'Controller'Admin;
use Silex'Application;
use Silex'ControllerProviderInterface;
class AdminDashboardProvider implements ControllerProviderInterface, ServiceProviderInterface
{
public function register(Application $app)
{
$app['controller.admin.index'] = $app->share(function () {
return new AdminIndexController();
});
}
public function connect(Application $app)
{
$controllers = $app['controllers_factory']();
$controllers->get('/', 'controller.admin.index:get');
return $controllers;
}
public function boot(Application $app)
{
$app->mount('/admin', $this);
}
}
控制器看起来像这样:
namespace App'Controller'Admin;
class AdminIndexController
{
public function get()
{
return 'Index Dashboard';
}
}
然后你可以在app/app.php
中用你的应用程序注册它,比如:
$app->register(new AdminDashboardProvider());