[英]Using PHP Slim Framework inside of Classes
I can't seem to get the Slim framework to access functions inside the scope of a PHP class: 我似乎无法使用Slim框架来访问PHP类范围内的函数:
<?php
class Controller {
private $app;
public function __construct() {
$this->app = new Slim();
$this->app->get('/', $this->home);
$this->app->run();
}
public function home() {
echo 'hi';
}
}
This causes the following error: 这会导致以下错误:
Fatal error: Uncaught exception 'ErrorException' with message 'Undefined property: Controller::$home' in /Users/Oliver/Dropbox/Sites/grapevine/application/controller.php:9 Stack trace: #0 /Users/Oliver/Dropbox/Sites/grapevine/application/controller.php(9): Slim::handleErrors(8, 'Undefined prope...', '/Users/Oliver/D...', 9, Array) #1 /Users/Oliver/Dropbox/Sites/grapevine/public/index.php(14): Controller->__construct() #2 {main} thrown in /Users/Oliver/Dropbox/Sites/grapevine/application/controller.php on line 9 致命错误:未捕获异常'ErrorException',消息'Undefined属性:Controller :: $ home'在/Users/Oliver/Dropbox/Sites/grapevine/application/controller.php:9堆栈跟踪:#0 / Users / Oliver / Dropbox /Sites/grapevine/application/controller.php(9):Slim :: handleErrors(8,'Undefined prope ...','/ Users / Oliver / D ...',9,Array)#1 / Users / Oliver / Dropbox / Sites / grapevine / public / index.php(14):控制器 - > __ construct()#2 {main}在第9行的/Users/Oliver/Dropbox/Sites/grapevine/application/controller.php中引发
I have tried doing this instead: 我试过这样做:
$this->app->get('/', $this->home());
But then the routing is ignored, and 'hi' is displayed on every page, not just '/'. 但是然后忽略路由,并且在每个页面上显示“hi”,而不仅仅是'/'。
使用成员函数的回调语法:
$this->app->get('/', array($this, 'home'));
以下应该可行(尽管如此,可能需要将home-function更改为静态!):
$this->app->get('/', "Controller::home");
I have this solution with constructor injection from Slim internal container 我有这个解决方案与Slim内部容器的构造函数注入
Basically the main magic is hidden in __call
function 基本上主要的魔法隐藏在__call
函数中
class App extends Slim
public function __call($name, $params) {
return function () use ($name, $params) {
list($class, $action) = explode('_', $name . '_handle'); // default method is handle
$args = [];
$class = new \ReflectionClass($class);
$constructor = $class->getConstructor();
foreach ($constructor->getParameters() as $param) {
$args[] = ($param->name === 'app') ? $this : $this->container->get($param->name);
}
$controller = $class->newInstanceArgs($args);
return call_user_func([$controller, $action], func_get_args() + $params);
};
}
}
controller need to have App in constructor params: 控制器需要在构造函数参数中使用App:
class Homepage {
public $app;
public function __construct(\App $app) {
$this->app = $app;
}
}
And index.php have just router settings 而index.php只有路由器设置
$app = new \App();
$app->get('/', $app->Homepage());
$app->run(
See whole code here https://gist.github.com/OzzyCzech/7230064 请在此处查看完整代码https://gist.github.com/OzzyCzech/7230064
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.